首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【HDU】1297 - Children’s Queue(BigDecimal & 递推 & 思维)

【HDU】1297 - Children’s Queue(BigDecimal & 递推 & 思维)

作者头像
FishWang
发布2025-08-27 09:23:40
发布2025-08-27 09:23:40
16900
代码可运行
举报
运行总次数:0
代码可运行

点击打开题目

Children’s Queue

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

代码语言:javascript
代码运行次数:0
运行
复制
   1
2
3

Sample Output

代码语言:javascript
代码运行次数:0
运行
复制
   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来做。

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
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]);
	    }
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Children’s Queue
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档