PAT_A1140#Look-and-say Sequence

Source:

PAT A1140 Look-and-say Sequence (20 分)

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 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 8

Sample Output:

1123123111

Keys:

  • 简单模拟

Attention:

  • 这种小题有时候还挺头疼的-,-

Code:

 1 /*
 2 Data: 2019-05-24 10:44:34
 3 Problem: PAT_A1140#Look-and-say Sequence
 4 AC: 44:30
 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 
18 #include<cstdio>
19 #include<string>
20 #include<iostream>
21 using namespace std;
22 
23 int main()
24 {
25 #ifdef    ONLINE_JUDGE
26 #else
27     freopen("Test.txt", "r", stdin);
28 #endif
29 
30     int n;
31     string s;
32     cin >> s >> n;
33     for(int i=1; i<n; i++)
34     {
35         string ans="";
36         int pt=0;
37         while(pt < s.size())
38         {
39             int cnt=1;
40             ans+=s[pt];
41             while(pt+1<s.size()&&s[pt]==s[pt+1]){
42                 cnt++;pt++;
43             }
44             ans+=('0'+cnt);
45             pt++;
46         }
47         s=ans;
48     }
49     cout << s;
50 
51     return 0;
52 }

猜你喜欢

转载自www.cnblogs.com/blue-lin/p/10917168.html