找规律的题,当时没看出来。
第n个数是对n-1个数的描述。
S(1)=1,
S(2)=11,//s[1]为1个1
S(3)=21,//s[2]为2个1
S(4)=1211,//s[3]为1个2,1个1
S(5)=111221,//s[4]为1个1,1个2,2个1
S(6)=312211,//s[5]为3个1,2个2,1个1
知道规律后就简单,由于case只有30个,果断打表。
打表的程序:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char str[1000000], next[1000000];
void solve (char *str, char next[])
{
int i = 1, j = 0, cnt = 1;
while (str[i] != '\0')
{
if (str[i] == str[i-1]) cnt++;
else {
next[j++] = cnt + '0';
next[j++] = str[i-1];
cnt = 1;
}
i++;
}
next[j++] = cnt + '0';
next[j++] = str[i-1];
next[j] = '\0';
//cout << str << " " << next << endl;
cout << j << ", ";
}
int main()
{
str[0] = '1'; str[1] = '\0';
for (int i = 1; i <= 30; i++)
{
solve(str, next);
strcpy(str, next);
}
return 0;
}
提交代码:
#include <iostream>
using namespace std;
int main()
{
short ans[32] = {1, 2, 2, 4, 6, 6, 8, 10, 14, 20, 26, 34, 46, 62, 78, 102, 134, 176, 226, 302, 408,
528, 678, 904, 1182, 1540, 2012, 2606, 3410, 4462};
short n;
while (cin >> n)
{
if (n == 0) break;
cout << ans[n-1] << endl;
}
return 0;
}