PAT_A1140#Look-and-say Sequence
Source:
Description:
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 oneD
in the 1st number, and hence it isD1
; the 2nd number consists of oneD
(corresponding toD1
) and one 1 (corresponding to 11), therefore the 3rd number isD111
; or since the 4th number isD113
, it consists of oneD
, two 1's, and one 3, so the next number must beD11231
. This definition works forD
= 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digitD
.
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 8
Sample Output:
1123123111
Keys:
- 简单模拟
Attention:
- 这种小题有时候还挺头疼的-,-
- to_string()
Code:
1 /* 2 Data: 2019-05-24 10:44:34 3 Problem: PAT_A1140#Look-and-say Sequence 4 AC: 17:49 5 6 题目大意: 7 观察并说出相应的序列; 8 比如给出第一个数字D,第二个数字为D1(D有1个) 9 第三个数字为D111(D有1个,1有1个); 10 第四个数字为D113(D有1个,1有3个); 11 以此类推.... 12 输入: 13 初始数字D,和轮次N 14 输出: 15 第N轮相应的序列 16 */ 17 #include<cstdio> 18 #include<string> 19 #include<iostream> 20 using namespace std; 21 22 int main() 23 { 24 #ifdef ONLINE_JUDGE 25 #else 26 freopen("Test.txt", "r", stdin); 27 #endif // ONLINE_JUDGE 28 29 int n; 30 string s; 31 cin >> s >> n; 32 for(int k=1; k<n; k++) 33 { 34 string t=""; 35 for(int i=0; i<s.size(); i++) 36 { 37 int cnt=1; 38 while(i+1<s.size() && s[i]==s[i+1]) 39 { 40 cnt++; 41 i++; 42 } 43 t += (s.substr(i,1)+to_string(cnt)); 44 } 45 s=t; 46 } 47 cout << s; 48 49 return 0; 50 }