首页 > ACM题库 > HDU-杭电 > HDU 1297 Children’s Queue-递推-[解题报告] C++
2013
12-04

HDU 1297 Children’s Queue-递推-[解题报告] C++

Children’s Queue

问题描述 :

There are many students in PHT School. One day, the headmaster whose name is PigHeader wanted all students stand in a line. He prescribed that girl can not be in single. In other words, either no girl in the queue or more than one girl stands side by side. The case n=4 (n is the number of children) is like
FFFF, FFFM, MFFF, FFMM, MFFM, MMFF, MMMM
Here F stands for a girl and M stands for a boy. The total number of queue satisfied the headmaster’s needs is 7. Can you make a program to find the total number of queue with n children?

输入:

There are multiple cases in this problem and ended by the EOF. In each case, there is only one integer n means the number of children (1<=n<=1000)

输出:

For each test case, there is only one integer means the number of queue satisfied the headmaster’s needs.

样例输入:

1
2
3

样例输出:

1
2
4

题目链接:hdu1297

一个长度n的队列可以看成一个n – 1的队列再追加的1个小孩,这个小孩只可能是:

a.男孩,任何n – 1的合法队列追加1个男孩必然是合法的,情况数为f[n - 1];
b.女孩,在前n – 1的以女孩为末尾的队列后追加1位女孩也是合法的,我们可以转化为n – 2的队列中追加2位女孩;
       一种情况是在n – 2的合法队列中追加2位女孩,情况数为f[n - 2];

       但我们注意到本题的难点,可能前n – 2位以女孩为末尾的不合法队列(即单纯以1位女孩结尾),也可以追加2位女孩成为合法队列,而这种n – 2不合法队列必然是由n – 4合法队列+1男孩+1女孩的结构,即情况数为f[n - 4]。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;
const int mod = 100000;
int a[1003][50];
int main()
{
    int n,i,j;
    a[1][1] = 1;
    a[2][1] = 2;
    a[3][1] = 4;
    a[4][1] = 7;
    for(i = 5; i <= 1000; i ++)
    {
        for(j = 1; j < 50; j ++)
        {
            a[i][j] += a[i-1][j] + a[i-2][j] + a[i-4][j];
            a[i][j+1] += a[i][j]/mod;
            a[i][j] %= mod;
        }
    }
    while(~scanf("%d",&n))
    {
        j = 49;
        while(!a[n][j])
        j--;
        printf("%d",a[n][j]);
        for(--j; j >=1; j--)
        printf("%05d",a[n][j]);
        printf("\n");
    }
    return 0;
}


  1. 嗯 分析得很到位,确实用模板编程能让面试官对你的印象更好。在设置辅助栈的时候可以这样:push时,比较要push的elem和辅助栈的栈顶,elem<=min.top(),则min.push(elem).否则只要push(elem)就好。在pop的时候,比较stack.top()与min.top(),if(stack.top()<=min.top()),则{stack.pop();min.pop();},否则{stack.pop();}.

  2. 站长好。我是一个准备创业的互联网小白,我们打算做一个有关国*际*游*学的平台。手上也有了一些境外资源。现阶段的团队现在没有cto.原意出让一些管理股寻找一个靠谱的技术专家做合伙人, 不知道是不是能得到您的帮助。发个帖子或者其他方式。期待您的回应。可以加我微信tianxielemon聊聊。