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

Sample Output:

1123123111


题意:
例:D, D1--(1个D), D111--(1个D 1个1), D113--(1个D 3个1), D11231--(1个D 2个1 1个3)

给出D和N
输出第n个数


测试得出 1 40

的长度为16138;可以确定范围


代码如下:
思路清晰就好做很多,我刚开始一直在一些细节上出问题,导致输出的很奇怪;注意int转char时+'0';

 


 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define ll long long
 4 char a[100000],b[100000];
 5 
 6 int main()
 7 {
 8     int d,n;
 9     cin >> d >> n;
10     a[0] = d + '0';
11     int co = 0;
12     char st;
13     if(n == 1)
14     {
15         cout << a[0] << endl;
16         return 0;
17     }
18     else
19     for(int i = 1;i < n;i++)
20     {
21         st = d + '0';//第一个数一直不会改变
22         int num = 0;//记录个数
23         int len = strlen(a);
24         for(int j = 0;j < len;j++)
25         {
26             if(a[j] == st)
27             num++;
28             else
29             {
30                 b[co++] = st;
31                 st = a[j];//更新st
32                 b[co++] = num + '0';
33                 num = 1;//更新num
34             }
35         }
36         b[co++] = st;//最后一个在循环里无法录入,所以单独记录
37         b[co++] = num + '0';
38         for(int i1 = 0;i1 < co;i1++)
39         a[i1] = b[i1];
40         co = 0;
41     }
42     cout << a << endl;
43     return 0;
44 }

 





posted @ 2018-12-07 20:20  lu_nacy  阅读(221)  评论(0编辑  收藏  举报