Children’s Queue |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 745 Accepted Submission(s): 418 |
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
|
Sample Output 1
|
来自 <http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=3§ionid=1&problemid=10>
分析:
这道题是典型的DP问题,想要得到第n个字母时符合条件的排列的个数有两种情况
1.当第n-1个字母排列是规范时,只有一种方法保持规范(F结尾则补F,M结尾则补M),故有1*F(n-1)种
2.当第n-1个字母排序不规范时,有两种情况,一个是能补规范,另一种补不规范了,如MMF(能),MFM(不能),所以这里只要求补得规范的情况
n-1不规范但补得规范的情况:
1.n-2规范且结尾为M结尾(F结尾n-1要不规范,要不补不全),有F(n-2)种
2.n-2不规范且是最后一位是F,倒数第二位是M,之前的都规范(其它情况都补不全),有F(n-4)种
所以有:F(n) = F(n-1) + F(n-2) + F(n-4)
这题给出n最大为1000,由上式得:F(n) > 3 * F(n-4) > F(1) * 3^250 > 3^250
呵呵~很明显这是Int_64都接纳不了的大数据,没办法,用数组模拟吧!
代码:
#include<iostream>
using namespace std;
int main()
{
charqueue[1000][500];
memset(queue,'0',sizeof(queue));
intsizeOfQueue[1000];
memset(sizeOfQueue,0,sizeof(sizeOfQueue));
queue[0][0]= '1';
queue[1][0]= '2';
queue[2][0]= '4';
queue[3][0]= '7';
for(inti = 4;i < 1000;i++)
{
intj = 0,jw = 0;
while(j<= sizeOfQueue[i-1])
{
queue[i][j]= queue[i-1][j] - '0' + queue[i-2][j] - '0' + queue[i-4][j] + jw ;
jw= (queue[i][j] - '0') / 10;
queue[i][j++]= (queue[i][j] - '0')%10 + '0';
}
if(jw> 0)
{
queue[i][j]= jw + '0';
sizeOfQueue[i]= j;
}
elsesizeOfQueue[i] = j - 1;
}
intn;
while(scanf("%d",&n)!= EOF)
{
for(inti = sizeOfQueue[n-1];i >= 0; i--)
printf("%c",queue[n-1][i]);
printf("\n");
}
return0;
}