hdu4148 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): 1406    Accepted Submission(s): 838


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
 
本题最重要的是找到规律,观察数据排列可以知道
S(1) = 1
S(2) = 11
S(3) = 21
S(4) = 1211
S(5) = 111221
S(6) = 312211
...
即 S(n) 与 S(n-1) 有关系 :S(1)有一个1 所以S(2) = 11, S(2)有2个1, 所以S(3) = 21 以此类推。
可以通过前一个推出后一个字符串,然后将所有情况枚举出来

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 2500; //每个字符串的长度未知,因此数组长度可以开大一点

char c[31][N];

void lengthS()
{

  int len, count, k;
  memset(c, 0, sizeof(c));//很容易忘记

  c[1][0] = '1';
  c[2][0] = '1';
  c[2][1] = '1';

  for(int i = 3; i <= 30; i++)//将所有的字符串枚举出来
  {
    len = strlen(c[i-1]);
    k = 0, count = 1;

    for(int j = 0; j < len; j++)
    {
      if(c[i-1][j] == c[i-1][j+1])
      {
        count++;
      }
      else
      {
        while(count)
        {
          c[i][k++] = count%10 + '0';// 记录个数
          count /= 10;
        }
        c[i][k++] = c[i-1][j];
        count = 1;
      }
    }
  }
}
int main()
{
  int n, len;
  lengthS();
  while(cin >> n && n)// n = 0时结束程序
  {
    len = strlen(c[n]);
    cout << len << endl;
  }
  return 0;
}

posted @ 2018-02-26 16:39  shirley-wang  阅读(468)  评论(0编辑  收藏  举报