Tiling
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9979 | Accepted: 4684 |
Description
In how many ways can you tile a 2xn rectangle by 2x1 or 2x2 tiles?
Here is a sample tiling of a 2x17 rectangle.
Here is a sample tiling of a 2x17 rectangle.
Input
Input is a sequence of lines, each line containing an integer number 0 <= n <= 250.
Output
For each line of input, output one integer number in a separate line giving the number of possible tilings of a 2xn rectangle.
Sample Input
2 8 12 100 200
Sample Output
3 171 2731 845100400152152934331135470251 1071292029505993517027974728227441735014801995855195223534251
这个题目拿到就是想到了递推,才看了这一题的,而且之前的个人赛中我写到这题的时候就找出了规律即F(N)=F(N-1)+F(N-2)*2。之前找出规律也是运气好,就是不停地写2×1、2×2……这样,然后就发现了他们每个数之间的规律,不过当时还不会大数运算(谁知道后来一开窍自己写了写这么简单……)。不过后来看了算法书,这题我就这么想:假设有2×n个,把第一个2×1的格子与2×(n-1)个分开看,2×1只有一种排法,而把2×2和2×(n-2)分开看,2×2有三种排法,而去掉前面的那种竖着的排法,就只有两种排法,如果再往后看2×3的格子就重复之前2×1的排法了,所以就是F(n)=F(n-2)*2+F(n-1)。下面是我的代码
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
static BigInteger dp[]=new BigInteger[300];
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int n;
dp[0]=BigInteger.valueOf(1);
dp[1]=BigInteger.valueOf(1);
dp[2]=BigInteger.valueOf(3);
for(int i=3;i<300;i++){
dp[i]=dp[i-1].add(dp[i-2].multiply(BigInteger.valueOf(2)));
}
while(in.hasNext()){
n=in.nextInt();
System.out.println(dp[n]);
}
}
}
本人也是比较蠢的,为什么这么说呢,之前交了无数次,一直WA,很纳闷输入248、249、250输出的数我验算都是对的,为什么总是WA!!后来,我才发现T=0那种情况,我开始写的是0,改成1交一次试试,没想到……AC =。=