您的位置:首页 > 产品设计 > UI/UE

HDUOJ 1297 - Children’s Queue(递推求解 + string大数相加)

2017-11-23 16:29 429 查看

原题

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个人的合法队列的最后一个人是男,则对前面n-1个人的队列没有任何限制,他只要站在最后即可,所以,这种情况一共有F(n-1);

如果n个人的合法队列的最后一个人是女,则要求队列的第n-1个人务必也是女生,这就是说,限定了最后两个人必须都是女生,这又可以分两种情况:

如果队列的前n-2个人是合法的队列,则显然后面再加两个女生,也一定是合法的,这种情况有F(n-2);

但是,难点在于,即使前面n-2个人不是合法的队列,加上两个女生也有可能是合法的,当然,这种长度为n-2的不合法队列,不合法的地方必须是尾巴,就是说,这里说的长度是n-2的不合法串的形式必须是“F(n-4)+男+女”,这种情况一共有F(n-4).

所以,通过以上的分析,可以得到递推的通项公式:

F(n)=F(n-1)+F(n-2)+F(n-4) (n>3)

然后就是对n<=3 的一些特殊情况的处理了

显然: F(0)=1 (没有人也是合法的,这个可以特殊处理,就像0的阶乘定义为1一样)

F(1)=1

F(3)=4

代码:

递推求解–找递推公式

#include<stdio.h>
#include <string>
#include <iostream>
using namespace std;
string dp[1001] = { "1","1","2","4" };
string BigNumAdd(string a, string b)
{
int A_Len = a.length() - 1, B_Len = b.length() - 1, i, temp, CarryBit = 0;
//前面补0,弄成长度相同
if (A_Len<B_Len)
{
for (i = 1;i <= B_Len - A_Len;i++)
a = "0" + a;
}
else
{
for (i = 1;i <= A_Len - B_Len;i++)
b = "0" + b;
}
//------
for (i = A_Len; i >= 0; i--)
{
temp = a[i] - '0' + (b[i] - '0') + CarryBit;
CarryBit = temp / 10;//进位
temp %= 10;
a[i] = char(temp + '0');
}
if (CarryBit != 0)a = char(CarryBit + '0') + a;
return a;
}
int main()
{
int  n, i;
for (i = 4; i <= 1000; i++)
dp[i] = BigNumAdd(BigNumAdd(dp[i - 1], dp[i - 2]), dp[i - 4]);
while (scanf("%d", &n) != EOF)
cout << dp
<< endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  递推求解 ACM 算法