HDOJ1297:Children’s Queue——递推求解、大数运算

Problem Description
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?

Input
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 (11、如果n个人的合法队列的最后一个人是男,则对前面n-1个人的队列没有任何限制,他只要站在最后即可,所以,这种情况一共有F(n-1);

  • 2、如果n个人的合法队列的最后一个人是女,则要求队列的第n-1个人务必也是女生,这就是说,限定了最后两个人必须都是女生,这又可以分两种情况:
  • 2.1、如果队列的前n-2个人是合法的队列,则显然后面再加两个女生,也一定是合法的,这种情况有F(n-2);
  • 2.2、但是,难点在于,即使前面n-2个人不是合法的队列,加上两个女生也有可能是合法的,当然,这种长度为n-2的不合法队列,不合法的地方必须是尾巴,就是说,这里说的长度是n-2的不合法串的形式必须是“F(n-4)+男+女”,这种情况一共有F(n-4).
  • 所以F(n)=F(n-1)+F(n-2)+F(n-4)。因为题目要求n取值在1000以内,超过了_int64的大小。所以要用大数运算来做。但是大数运算至今没搞懂,就直接从网上找了大数的模板了……

    代码:

    #include
    #include
    #include
    using namespace std;
    long long s[1010][1005];
    int main()
    {
        int i,j,n;
        memset(s,0,sizeof(s));
        s[1][0]=1;s[2][0]=2;s[3][0]=4;s[4][0]=7;
        for(i=5;i=10){
                    s[i][j+1]+=s[i][j]/10;
                    s[i][j]%=10;
                }
           }
        }
    
        while(cin>>n){
            i=1000;
            while(i--){
                if(s[n][i]!=0)
                    break;
            }
            cout=0;i--)
                printf("%d",s[n][i]);
            cout
    
    	

    发表评论

    您的电子邮箱地址不会被公开。 必填项已用*标注