hdu-1297(找规律+大数加法)

来源:互联网 发布:淘宝api 生成淘口令 编辑:程序博客网 时间:2024/06/05 11:57
Children’s Queue

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10643    Accepted Submission(s): 3430

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

思路:分男女生考慮,設總共有n個人(f(n)表示當有n個人的時候合法序列的個數,ak表示第k個人),當a1為男生時,有f(n-1)種可能,當a1是女生時,a2必為女生;當a1、a2都為女生時,a3為男生,有f(n-3)種可能,當a1、a2、a3都為女生,a4為男生時,有f(n-4)種可能,以此類推(下式中1表示n全為女生時那種情況,規定f(0) = 1),
故有 f(n) = f(n-1) + f(n-3) + f(n-4) + f(n-5) + ... + f(1) + f(0) + 1;
所以 f(n-2) =       f(n-3) +         f(n-5) + f(n-6) + ... + f(1) + f(0) + 1;

由以上兩式得 f(n) = f(n-1) + f(n-2) + f(n-4)

#include<iostream>#include<string>#include<stdio.h>using namespace std;string fs(string a,string b){string c;int la=a.length()-1;int lb=b.length()-1;int k=0;while(la>=0||lb>=0){if(la>=0&&lb>=0){c=char((a[la]+b[lb]-96+k)%10+48)+c;k=(a[la]+b[lb]-96+k)/10;la--;lb--;}else if(la>=0){c=char((a[la]-48+k)%10+48)+c;k=(a[la]+k-48)/10;la--;}else if(la>=0){c=char((b[lb]-48+k)%10+48)+c;k=(b[lb]+k-48)/10;lb--;}}if(k!=0) c=char(k+48)+c;return c;}string f[1001];int main(){int n,m;f[1]="1";f[2]="2";f[3]="4";f[4]="7";for(int i=5;i<=1000;i++){string y;y=fs(f[i-1],f[i-2]);f[i]=fs(y,f[i-4]);}while(scanf("%d",&n)!=EOF)cout<<f[n]<<endl;return 0;}


0 0