点击打开题目
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 13723 Accepted Submission(s): 4496
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
Author
SmallBeer (CML)
Source
杭电ACM集训队训练赛(VIII)
这个递推也有点难想(其实是容易想错),之前有一个LELE的RPG难题和这个类似。
现在说一下这个题的推理:我们考虑当前情况的最后一个人
①如果是男生,那么就是 f(i - 1);
②如果是女生,而f(i - 1)的最后一个有可能是男生,这样就违反了题目的要求。我们考虑f(i - 2)在后面直接放两个女生就满足了条件。而想到这里并没有结束(就wa在这里了),还有一种情况,如果f(i - 2)的最后只有一女生(这种情况在f(i - 2)中不存在,但是在f(i)中可能存在,即连续三个女生。)这个时候就应该加上f(i - 4)(即f(i - 4)后面放一个男生 + 一个女生 + 两个女生)。
所以递推公式为 :
f(n)= f(n - 1)+ f(n - 2)+ f(n - 4)
这个数还是非常大的,所以我选择了用java的BigDecimal来做。
代码如下:
import java.math.BigDecimal;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
BigDecimal f[] = new BigDecimal [1011];
f[1] = new BigDecimal(1);
f[2] = new BigDecimal(2);
f[3] = new BigDecimal(4);
f[4] = new BigDecimal(7);
for (int i = 5 ; i <= 1000 ; i++)
{
f[i] = f[i-1].add(f[i-2]).add(f[i-4]);
}
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
int n = sc.nextInt();
System.out.println(f[n]);
}
}
}