給定長度 N (≤20) 的字母數字串(大寫字母 A-Z 或數字 0-9),按規則反覆突變直到穩定:
輸出最終穩定後的字符串。
int mutate(int pos) 返回從 pos 開始的段總突變次數,並原地修改字符串。
int mutate(int pos) {
if (pos >= n || s[pos] == '0') return 0;
if (isalpha(s[pos])) { // 字母
int cnt = mutate(pos + 1);
s[pos] = '0' + (cnt > 9 ? cnt % 10 : cnt);
return 1 + cnt;
}
// 數字 1-9
int step = s[pos] - '0';
int cnt;
if (pos + step < n) cnt = mutate(pos + step);
else cnt = mutate(pos + 1);
s[pos]--; // 變為 n-1
return 1 + cnt;
}
#include#include #include int n; char s[21]; int mutate(int pos) { if (pos >= n || s[pos] == '0') return 0; if (isalpha(s[pos])) { int cnt = mutate(pos + 1); s[pos] = '0' + (cnt > 9 ? cnt % 10 : cnt); return 1 + cnt; } int step = s[pos] - '0'; int cnt = (pos + step < n) ? mutate(pos + step) : mutate(pos + 1); s[pos]--; return 1 + cnt; } int main() { char cmd[20]; while (scanf("%s", cmd) == 1) { if (strcmp(cmd, "ENDOFINPUT") == 0) break; scanf("%d\n", &n); scanf("%s", s); scanf("%s", cmd); // 讀掉 "END" mutate(0); printf("%s\n", s); } return 0; }
輸入 START 4 / A1B2 / END:
3011,匹配樣例輸出。pos + step < n 判斷邊界,越界則退回 pos+1。START N、END、ENDOFINPUT 多行,需仔細讀取換行符。