1. 程式人生 > >pta 1140 Look-and-say Sequence (20 分)

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 }