HDU--1297--排列组合问题

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

思路:不知道wa了多少次,思路是:
递推式子:f(n)=f(n-4)+f(n-2)+f(n-1),后来注意到此题是大数问题,当前代码无法解决;

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int MAX=1000+1;
long long f[MAX];
void init(){
	f[1]=1;f[2]=2;f[3]=4;f[4]=7;
	for(int i=5;i<=MAX;i++)
		f[i]=f[i-1]+f[i-2]+f[i-4];
}
int main(){
	int n;
	init();
	while(scanf("%d",&n)!=EOF){
		printf("%lld\n",f[n]);
	}
} 

AC代码:

#include <iostream>
#include <cstring>
#include<cstdio>
char dashu[1005][1000];
using namespace std;
void add(int a,int b){
    int len_a,len_b;
    len_a=strlen(dashu[a]);
    len_b=strlen(dashu[b]);
    int zf=0;           //代表进位
    int i=0;
    int ta,tb,d;             //ta,tb分别代表该位的数值  
    while(i<len_a||zf==1){
        ta=tb=0;
        if(i<len_a)
            ta=dashu[a][i]-'0';
        if(i<len_b){
            tb=dashu[b][i]-'0';
        }
        d=ta+tb+zf;
        d=d>9?d-10:d;
        if(ta+tb+zf>9){
            zf=1;
        }
        else{
            zf=0;
        }
        dashu[a][i]='0'+d;
        i++;
    }
}
void printDashu(int a){
    int len=strlen(dashu[a]);
    for(int i=len-1;i>=0;i--)
        cout<<dashu[a][i];
    cout<<endl;
}
int main(){
    int n;
    dashu[1][0]='1';
    dashu[2][0]='2';
    dashu[3][0]='4';
    dashu[4][0]='7';
    for(int i=5;i<=1000;i++){
        strcpy(dashu[i],dashu[i-1]);
        add(i,i-2);
        add(i,i-4);
    }
    while(cin>>n){
        printDashu(n);
    }
    return 0;
}
发布了170 篇原创文章 · 获赞 73 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/104454986