题目链接
题目
You will be given a string which only contains ‘1’; You can merge two adjacent ‘1’ to be ‘2’, or leave the ‘1’ there. Surly, you may get many different results. For example, given 1111 , you can get 1111, 121, 112,211,22. Now, your work is to find the total number of result you can get.
Input
The first line is a number n refers to the number of test cases. Then n lines follows, each line has a string made up of ‘1’ . The maximum length of the sequence is 200.
Output
The output contain n lines, each line output the number of result you can get .
Sample Input
3
1
11
11111
Sample Output
1
2
8
题意
给定一个只由“1”组成的字符串s,相邻的两个“1”可以合并成“2”。比如“1111”可以组成字符串”1111“,”121“,”112“,”211“,”22“。这5个不重复的字符串。
现要求s可以组成的字符串的个数。
分析
设F(i)表示字符串长度为i的字符串可以组成的字符串的个数。
根据题意,可以得知:
F(1)=1;
F(2)=2;
F(3)=3;
F(4)=5;
F(5)=8;
F(6)=13;
观察规律,可以得到:
F(i)=F(i-1)+F(i-2),i>2;
然后用JAVA处理大数问题即可。
AC代码
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int n;
n=cin.nextInt();
for(int i=1;i<=n;i++) {
int x;
String s;
s=cin.next();
x=s.length();
BigInteger a,b,c;
a=BigInteger.ONE;
b=a.add(a);
c=a;
if(x==2) c=b;
for(int j=3;j<=x;j++) {
c=a.add(b);
a=b;
b=c;
}
System.out.println(c);
}
}
}