题目:
S(1)=1,
S(2)=11,S(3)=21,
S(4)=1211,
S(5)=111221,
S(6)=312211,
....
求S(n)的长度。
思路:
题目很简单就是压缩字符串, 比如:s[4] = 1211 那么是s[5]中内容就是1一个1即11, 一个2即12和2个1即21, 合起来s[5]就是11 12 21
同理s[5] = 111221 那么s[6]就是3个1即31, 2个2即22, 1个1即11合起来就是31 22 11;
代码如下
#include <iostream>
using namespace std;
#define N 5000
char str[31][N];
void init()
{
int i, j, count, k, n;
memset(str, 0, sizeof(str));
str[1][0] = '1';
str[2][0] = '1';
str[2][1] = '1';
for (i = 3;i <= 30 ; ++i)
{
k = 0;
n = strlen(str[i - 1]);
count = 1;
for (j = 0; j < n; ++j)
{
if (str[i - 1][j] == str[i - 1][j + 1])
{
++count;
}
else
{
while(count)
{
str[i][k++] = count % 10 + '0';
count /= 10;
}
str[i][k++] = str[i - 1][j];
count = 1;
}
}
}
}
int main()
{
int n;
init();
while(scanf("%d", &n) != EOF && n)
{
int len = strlen(str[n]);
printf("%d\n", len);
}
return 0;
}