HDUACM 1297 Children’s Queue(递…

Children’s Queue

 

Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)

 

Total Submission(s) : 251 Accepted Submission(s) : 65

 

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 (1<=n<=1000)
 

Output

 

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

Sample Input

 

1
2
3

Sample Output

 

1
2
4
我的分析:
1.首先,n个人时,假设n个人的组合是合法的,这样的一个合法的组合设为f(n)
2.为了保证n个人的时候是合法的,讨论一下第n个位置的人的性别
(1)如果第n个人是男性,那么前n-1个人,无论是什么样的组合,显然都是能保证n个人的组合是合法的,所以是f(n-1)
(2)如果第n个是女性的话,那么第n-1个人的性别必须是女性,这样才能保证n个人的组合是合法的!
然后我们需要考虑前n-2个人在合法与不合法这两种情况下都能使n个人的组合都合法的问题 。
*如果前n-2个人的组合是合法的,那么这个组合为f(n-2)
*如果前n-2的人的组合是不合法的话,那么这个组合只能是下图的情况HDUACM <wbr>1297 <wbr>Children鈥檚 <wbr>Queue(递归加大数加法)

         所以得到的递推公式就是f(n)=f(n-1)+f(n-2)+f(n-4)
 
网上找的源代码:(由于大数的计算暂时还没有完全搞懂,所以先从网上找到了一个比较好的源代码,用的大数模板,感觉很不错,过些天会重新发一下这个博客,然后贴上自己的代码,当然,上面的分析是自己的写的)
 
C++语言:
#include<iostream> 
#include<string>  
using namespace std
string add( string s1 , string s2
{ 
         
      int j , l , la , lb
      string max , min
      max = s1; min = s2
      if( s1 . length() < s2 . length()) { max = s2; min = s1 ;} 
      la = max . size(); lb = min . size(); 
      l = la - 1
      for( j = lb - 1; j >= 0; j -- , l --) max [ l ] += min [ j ] - '0';                                                //用到加法运算符,全部按照asiic码表来,就会多加一次48,所以要减去ascii值为48的‘0’ 
      for( j = la - 1; j >= 1; j --) if( max [ j ] > '9' ){ max [ j ] -= 10; max [ j - 1 ] ++ ;} 
      if( max [ 0 ] > '9') { max [ 0 ] -= 10; max = '1' + max ;} 
      return max
} 
int main ()
{
      int n , i
      string a [ 1001 ]; 
      a [ 0 ] = "1"
      a [ 1 ] = "1"
      a [ 2 ] = "2"
      a [ 3 ] = "4"
      for( i = 4; i < 1001; ++ i
            a [ i ] = add( add( a [ i - 1 ], a [ i - 2 ]), a [ i - 4 ]); 
        while( cin >>n) 
              cout << a [n ] << endl
      return 0;           
}

你可能感兴趣的:(HDUACM 1297 Children’s Queue(递…)