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

本文探讨了一个有趣的儿童队列排列问题,通过分析合法队列的条件,即女生要么不存在要么至少两个相邻,提出了一种递推算法来计算满足条件的不同队列数量。该算法使用了动态规划的思想,并通过预计算的方式提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值