1140. Look-and-say Sequence (20)
Look-and-say sequence is a sequence of integers as the following:
D, D1, D111, D113, D11231, D112213111, ...
where D is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one D in the 1st number, and hence it is D1; the 2nd number consists of one D (corresponding to D1) and one 1 (corresponding to 11), therefore the 3rd number is D111; or since the 4th number is D113, it consists of one D, two 1's, and one 3, so the next number must be D11231. This definition works for D = 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D.
Input Specification:
Each input file contains one test case, which gives D (in [0, 9]) and a positive integer N (<=40), separated by a space.
Output Specification:
Print in a line the Nth number in a look-and-say sequence of D.
Sample Input:1 8Sample Output:
1123123111
和乙级 1084. 外观数列 (20) 是一个题。
题意不太好懂,是一个模拟的过程。对于样例的解释:
第1项:1
第2项:11
第3项:12
第4项:1121
第5项:122111
第6项:112213
第7项:12221131
第8项:1123123111
如果你只是把题目中的d替换成1就不对了,拿d = 1举例,每新产生的一项包含新的1,下次推导就不对了。
实现的思路就是模拟这个推导过程。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string str;
string num = "0123456789";
string intToString( int n ) {
string ans;
while( n ) {
ans = ans + num[n % 10];
n = n / 10;
}
reverse( ans.begin(), ans.end() );
return ans;
}
void nextString() {
string ans;
int len = str.size();
char pre = '#';
int cnt = 1;
for( int i = 0; i < len; i++ ) {
if( pre == str[i] ) cnt++;
else if( pre != str[i] && pre != '#' ) {
ans = ans + pre + intToString( cnt );
cnt = 1;
}
pre = str[i];
}
ans = ans + pre + intToString( cnt );
str = ans;
//cout << str << endl;
}
int main() {
int n;
cin >> str >> n;
for( int i = 2; i <= n; i++ ) {
nextString();
}
cout << str << endl;
return 0;
}
另外是用C语言的做法,用char*处理非常快。就是不太好写,需要把坑注意一下。另外需要把数组定义到足够大,因为最大是第40项,这个字符串非常长。很少用C语言刷题,代码写的略乱,凑合看吧。
// 用C语言的char*速度比较快,但是需要把数组开到足够大
#include <cstdio>
#include <cstring>
#define MAX 80000
char str[MAX];
char ans[MAX];
void nextString() {
ans[0] = '\0';
int len = strlen( str );
char pre = '#';
int cnt = 1;
for( int i = 0; i < len; i++ ) {
if( pre == str[i] ) cnt++;
else if( pre != str[i] && pre != '#' ) {
char t[2]; t[0] = pre; t[1] = '\0';
strcat( ans, t );
char temp[10];
sprintf( temp, "%d", cnt );
strcat( ans, temp );
cnt = 1;
}
pre = str[i];
}
char t[2]; t[0] = pre; t[1] = '\0';
strcat( ans, t );
char temp[10];
sprintf( temp, "%d", cnt );
strcat( ans, temp );
strcpy( str, ans );
//printf( "%s\n", str );
}
int main() {
int n;
scanf( "%s%d", str, &n );
for( int i = 2; i <= n; i++ ) {
nextString();
}
printf( "%s\n", str );
return 0;
}