(HDOJ)Children's Queue(java大數大法好)
前言
首先看一個對大數類的介紹和一些常用的方法連結,在大數中沒有傳統的+,-,*,/等等,都是封裝好的方法,而且對於處理一些ACM中的大數問題,可以用java大數很快解決,java大數大法好!!!
看一下這道題:
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)
題目思路的話,我直接貼上老師給的問題分析吧,因為這道題對於我來說真的太難。
老師思路
設:F(n)表示n個人的合法佇列,則:
按照最後一個人的性別分析,他要麼是男,要麼是女,所以可以分兩大類討論: 1、如果n個人的合法佇列的最後一個人是男,則對前面n-1個人的佇列沒有任何限制,他只要站在最後即可,所以,這種情況一共有F(n-1); 2、如果n個人的合法佇列的最後一個人是女,則要求佇列的第n-1個人務必也是女生,這就是說,限定了最後兩個人必須都是女生,這又可以分兩種情況: 2.1、如果佇列的前n-2個人是合法的佇列,則顯然後面再加兩個女生,也一定是合法的,這種情況有F(n-2); 2.2、但是,難點在於,即使前面n-2個人不是合法的佇列,加上兩個女生也有可能是合法的,當然,這種長度為n-2的不合法佇列,不合法的地方必須是尾巴,就是說,這裡說的長度是n-2的不合法串的形式必須是“F(n-4)+男+女”,這種情況一共有F(n-4). 所以,通過以上的分析,可以得到遞推的通項公式: F(n)=F(n-1)+F(n-2)+F(n-4) (n>3)然後就是對n<=3 的一些特殊情況的處理了,顯然:F(0)=1 (沒有人也是合法的,這個可以特殊處理,就像0的階乘定義為1一樣) F(1)=1 F(2)=2 F(3)=4
AC程式碼
import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner s=new Scanner(new BufferedInputStream(System.in));
BigInteger []a=new BigInteger[1011];
a[0]=BigInteger.ONE;
a[1]=BigInteger.ONE;
a[2]=BigInteger.valueOf(2);
a[3]=BigInteger.valueOf(4);
for(int i=4;i<=1010;i++){
a[i]=a[i-1].add(a[i-2]).add(a[i-4]);
}
while(s.hasNext()){
int n=s.nextInt();
System.out.println(a[n]);
}
}
}
對於用java提交這種AC程式碼,有一些格式要求。比如:
- 不能有包名,等等二級多級資料夾
- 方法體一定要有main方法
- 類名一定為Main
- …..
還有一些要求請參考杭電FAQ