Children’s Queue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10272 Accepted Submission(s): 3289
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?
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
Author
SmallBeer (CML)
Source
Recommend
lcy
题意:男女站一排,不能有单个女生自己站的情况,
例如:n = 4 则站排情况如下:(F表示女,M表示男)FFFF, FFFM, MFFF, FFMM, MFFM, MMFF, MMMM 结果为7
n = 3 .......................FFM, FFF, MMM, MFF 结果为4
n = 2.........................MM ,FF 结果为2
n = 1.........................M 结果为1
题解:
F(n)表示n个人的合法队列, 根据最后一个人是男是女分为两类:
1)最后一人是男人,则对前面n-1个人的队列武任何限制,他站在最后,这种情况共有F(n -1)种
2)最后一人是女人,则倒数第二人必须是女生,男生情况则不合法,这种情况又分两种情况:
2.1)如果前F(n - 2)人合法,则加两个女生也合法,所以这种情况共有F(n - 2)种;
2.2) 如果前F(n - 2)人不合法,加上2个女生也可能成为合法队列,这种情况只可能为
F(n - 4) + 男 + 女 这种情况 ,所以这种情况共有F(n - 4)种
综上所述,F(n) = F(n - 1) + F(n - 2) + F(n - 4) ,随后就是n<=3情况的特殊除了
需要说明的是F(0) = 1根据题意也是合法的,特殊情况
超时的递归代码:现在做这种题如果不打表或是找规律,基本就是超时
/******************************
*
* acm: hdu-1297
*
* title: Children’s Queue
*
* time: 2014.5.18
*
******************************/
//考察递推求解
#include <stdio.h>
#include <stdlib.h>
int fun(int n)
{
int res;
if (n == 0) //特殊处理
{
res = 1;
}
else if (n == 1)
{
res = 1;
}
else if (n == 2)
{
res = 2;
}
else if (n == 3)
{
res = 4;
}
else
{
res = fun(n-1) + fun(n-2) + fun(n-4);
}
return res;
}
int main()
{
int n;
while (~scanf("%d", &n))
{
printf("%d\n", fun(n));
}
return 0;
}
//我用打表方法做,但是还是错误,原来是高精度问题,当值为1000时,值大到 __int64 也会溢出
/******************************
*
* acm: hdu-1297
*
* title: Children’s Queue
*
* time: 2014.5.18
*
******************************/
//考察递推求解
//本题打表求解
#include <stdio.h>
#include <stdlib.h>
#define ll __int64
ll Array[1000];
void fun(int n)
{
int i;
Array[0] = 1;
Array[1] = 1;
Array[2] = 2;
Array[3] = 4;
for (i = 4; i < n; i++)
{
Array[i] = Array[i-1] + Array[i-2] + Array[i-4];
}
}
int main()
{
int n;
fun(1001);
while (~scanf("%d", &n))
{
printf("%I64d\n", Array[n]);
}
return 0;
}
//AC代码 ,递推+ 高精度