PAT 1084 外觀數列
阿新 • • 發佈:2018-12-05
num top ans bsp stack 要求 can scan ret 。當然這個定義對
https://pintia.cn/problem-sets/994805260223102976/problems/994805260583813120
外觀數列是指具有以下特點的整數序列:
d, d1, d111, d113, d11231, d112213111, ...
它從不等於 1 的數字 d
開始,序列的第 n+1 項是對第 n 項的描述。比如第 2 項表示第 1 項有 1 個 d
,所以就是 d1
;第 2 項是 1 個 d
(對應 d1
)和 1 個 1(對應 11),所以第 3 項就是 d111
。又比如第 4 項是 d113
,其描述就是 1 個 d
,2 個 1,1 個 3,所以下一項就是 d11231
d
= 1 也成立。本題要求你推算任意給定數字 d
的外觀數列的第 N 項。
輸入格式:
輸入第一行給出 [0,9] 範圍內的一個整數 d
、以及一個正整數 N(≤ 40),用空格分隔。
輸出格式:
在一行中給出數字 d
的外觀數列的第 N 項。
輸入樣例:
1 8
輸出樣例:
1123123111
代碼:
#include <cstdio> #include <string> #include <stack> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 1e5 + 10; int n, d; int sz, val[maxn], cnt[maxn]; int len[maxn]; char ans[50][maxn]; void work(int idx) { sz = 0; int num = 1; for (int i = 1; i < len[idx]; i++) { if (ans[idx][i] == ans[idx][i - 1]) { num++; } else { val[sz] = ans[idx][i - 1] - ‘0‘; cnt[sz] = num; sz++; num = 1; } } val[sz] = ans[idx][len[idx] - 1] - ‘0‘; cnt[sz] = num; sz++; for (int i = 0; i < sz; i++) { ans[idx + 1][len[idx + 1] ++] = (char)(val[i] + ‘0‘); stack<int> st; while (cnt[i]) { st.push(cnt[i] % 10); cnt[i] = cnt[i] / 10; } while (!st.empty()) { ans[idx + 1][len[idx + 1] ++] = (char)(st.top() + ‘0‘); st.pop(); } } } int main() { scanf("%d%d", &n, &d); len[1] = 1; ans[1][0] = (char)(n + ‘0‘); for (int i = 1; i < d; i++) { work(i); } cout << ans[d] << endl; return 0; }
PAT 1084 外觀數列