HDU1297:Children’s Queue(递推 + 大数加法) 好题

Children’s Queue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17284 Accepted Submission(s): 5796

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的情况往前考虑: (放 or 不放) + *(内否放了使之前不合法的变合法)

  1. 若n是男生,则只要往前每个f(n-1)情况中插入一个男生即可。
  2. 若n是女生:
    a.往之前合法的情况插入一个女生,即f(n-2) + 女女a.往之前合法的情况插入一个女生,即f(n-2) + 女女。
    b. * 若之前f(n-2)时有种非法的情况结尾为 “男女” ,后来加上“女女”后变为 “男女女女”合法了,所以即为f(n-4) + “男女女女”

这道题想到非法变为合法的情况就结束了吗?还是too naive…到1000时的数据会超过long long int 的范围,自己输入1000实验就行,这就要用到大树相加模板 ,创建的dp数组也得为string类型。

下面附上ac代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <ctype.h>
#include <queue>
#define INF 0x7ffffff
using namespace std;
typedef long long int ll;
string dp[1050];
string sum(string s1,string s2) { //大数相加模板
    if(s1.length() < s2.length()) {string temp = s1;s1 = s2; s2 = temp;}
    int i,j;
    for(i = s1.length() - 1,j = s2.length() - 1;i >= 0;i--,j--){
        s1[i] = char(s1[i] + (j >= 0?s2[j] - '0':0));
        if(s1[i] - '0' >= 10){
            s1[i] = char((s1[i] - '0') % 10 + '0');
            if(i) s1[i-1] ++;
            else s1 = '1' + s1;
        }
    }
    return s1;
}
int main() {
    dp[1] = '1';
    dp[2] = '2';
    dp[3] = '4';
    dp[4] = '7';
    for(int i = 5;i < 1010; i++) {
        dp[i] = sum(sum(dp[i-1],dp[i-2]),dp[i-4]);
    }
    int n;
    while(cin >> n){
        cout << dp[n] << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43555854/article/details/86557954
今日推荐