HDU 4148 Length of S(n) 【找规律+字符串】

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;
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值