HDU-4148-Length of S(n)
今天我们来看看我最近刷的一道编程题。
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
表面上看这道题貌似是道很简单的题目,然而我们发现自己连这个数列规律也没找到,哭了,我也是百度才知道的规律,好端端一个编程题搞成了找规律题,实在是匪夷所思。
废话不多说,规律是这样的:
我们知道第一个数列 S1=“1”,也就是说S1是一个1,那么S2就是S2=“11”,S2是两个1,那么S3就是S3=“21”,S3是一个2一个1那么S4=“1211”,以此类推,小伙伴们应该都懂了吧。
那么题目让我们输出串长,我一开始是想把这个串长的变化规律给找出来,然后去搞个公式,但是即使我写到S10我也不知道这个规律是啥(⊙_⊙)?
所以只能换个思路了,既然我们自己可以推出下一个串是什么,那么我们就让机器去像我们一样推导下一个串,最后输出串长就好了。
这里的串我们选择string,string 做为c++预制的类,使用起来不仅比char数组安全,还有各种函数让你用,自然方便很多。
推导思路:
把一个串看成不同重复串的组合,例如一个串“111233”,他可以看成“111”,“2”,“33”,那么无论这些重复串有多长,都会变成字符数+字符,即“111”->“31”,2->“12”,“33”->“23”。那么我们就可以在字符串中遍历,储存重复串的串长和字符值,每次遍历到重复串的结束就在新串后面添加“串长+字符值”,最后得到新串。
代码如下:
#include<iostream>
#include<string>
using namespace std;
string new_string(string a)//生成新串的函数
{
string new_str;
char get_char=a[0];//储存当前遍历的字符的值
int num = 1;//计算一个字符的重复次数
char t;
for (int i = 1; i < a.size(); i++)
{
if (a[i] == get_char)
num++;
else
{
t = num + '0';//t=一个字符的重复次数
new_str += t;//将t添加到字符串尾
new_str += get_char;//将字符添加到字符串尾
get_char = a[i];
num = 1;
}
}
t = num + '0';
new_str += t;
new_str += get_char;//for循环未能将字符串尾添加到新字符串,所以需要再次添加
return new_str;
}
int main()
{
string a;
int n;
while (cin >> n && n != 0)
{
a = "1";//第一个字符串
for (int i = 1; i < n; i++)
{
a = new_string(a);//生成第n个字符串
}
cout << a.size() << endl;//输出他的大小
}
return 0;
}