Children’s Queue(递推 + JAVA大数)

来源:互联网 发布:linux服务器份额 编辑:程序博客网 时间:2024/05/22 05:04

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

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

//题目中的意思合法的序列必须为 一个女生都没有 或者至少有两个女相邻
我们可以假设女生:0 男生:1
假设前n-1位都是一个合法的序列 所以当插入第n位时可以分为两种情况
1:当最后一位为男生时 此时的种为f[n-1] *1 = f[n-1]
2:当最后一名为女生时 那么根据题意第n-1位一定也是一个女生 此时又可以分为两种情况
当前n-2为一个合法的序列 那么此时的种数为 f[n-2] * 1
当前n-1为一个不和法的序列 那么此时序列一定是f[n-4] + 男 + 女 所以此时种数为f[n-4]\
所以总的种数为
f[n] = f[n-1] + f[n-4] + f[n-2];

import java.math.BigInteger;import java.util.Scanner;public class Main {    public static void main(String[] args) {        int n;        Scanner cin = new Scanner(System.in);        BigInteger[] qq = new BigInteger[1001];        qq[1] = BigInteger.ONE;        qq[2] = qq[1].add(BigInteger.ONE);        qq[3] = BigInteger.valueOf(4);        qq[4] = BigInteger.valueOf(7);        for (int i = 5; i <= 1000; i++)        {            qq[i] = qq[i-1].add(qq[i-4]).add(qq[i-2]);        }        while (cin.hasNext()) {            n = cin.nextInt();            System.out.println(qq[n]);        }    }}
原创粉丝点击