Length of S(n)
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 990 Accepted Submission(s): 590
Problem Description
A number sequence is defined as following:
S(1)=1,
S(2)=11,
S(3)=21,
S(4)=1211,
S(5)=111221,
S(6)=312211,
……
Now, we need you to calculate the length of S(n).
Input
The input consists of multiple test cases. Each test case contains one integers n.
(1<=n<=30)
n=0 signal the end of input.
Output
Length of S(n).
Sample Input
2 5 0
Sample Output
2 6
/*题解:
很有意思的一个题,找规律。然后用string处理。
规律:
a[1]="1"
a[2]="11" ,上一个由1个1组成
a[3]="21" , 上一个由2个1组成
a[4]="1211",上一个由1个2,1个1组成
*/
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
string a[110];
void f()
{
int t,i,j,k;
a[1]="1";
a[2]="11";
for(i=3; i<=30; i++)
{
int len=a[i-1].length();
for(j=1,t=1; j<len; j++)
{
if(a[i-1][j]==a[i-1][j-1])
{
t++;
}
else
{
a[i]+=char(t+'0');
a[i]+=a[i-1][j-1];
t=1;
}
}
if(j==len)//a[i-1][len-1]也要处理
{
a[i]+=char(t+'0');
a[i]+=a[i-1][j-1];
}
//cout<<a[i]<<endl<<endl;
}
}
int main()
{
int n;
f();
while(scanf("%d",&n)&&n)
{
int len=a[n].length();
printf("%d\n",len);
}
return 0;
}