(大数+递推)Children’s Queue

时间:2023-01-20 17:36:46

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? 
InputThere 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)OutputFor 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个学生排队的情况数为f[n]。

对于f[n]可分为以下几种情况:

如果第n个学生是男生,那么前n-1个学生排列满足条件即可;

如果第n个学生是女生,那么第n-1个也一定是女生,对于这种情况只要考虑前n-2个学生的排列情况即可。如果前n-2个学生排列满足条件,当然可以;如果前n-2个学生排列不满足条件,也有使总体满足条件的可能,即第n-2排女生,第n-3个排男生,此时只要前n-4个学生排列满足条件即可。

综上,f[n]=f[n-1]+f[n-2]+f[n-4].(n>4)

此外,递推需要分析不合理情况的,类似的还有排队购票这个题目。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		BigInteger f[]=new BigInteger[1010];
		f[1]=BigInteger.valueOf(1);
		f[2]=BigInteger.valueOf(2);
		f[3]=BigInteger.valueOf(4);
		f[4]=BigInteger.valueOf(7);
		for(int i=5;i<1010;i++){
			f[i]=f[i-1].add(f[i-2]).add(f[i-4]);
		}
		int n;
		while(sc.hasNext()){
			n=sc.nextInt();
			System.out.println(f[n]);
		}
	}
}