題目分析
這道題的輸入處理起來有點麻煩,要用gets讀取一行,注意前面還有一個空格。然後就是找迴圈節,用vector儲存,每個vector的大小就是一個迴圈節的大小,然後處理一下即可,之一每個案例結束後還要加一個分行符號。
#include <cstdio>#include <vector>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 205;int a[maxn], vis[maxn];vector <int> vec[maxn];char s[maxn];int main(){ int n, m; while(scanf("%d", &n) != EOF && n){ for(int i = 1; i <= n; i++) scanf("%d", &a[i]); memset(vis, 0, sizeof(vis)); for(int i = 0; i < maxn; i++) vec[i].clear(); int tot = 0; for(int i = 1; i <= n; i++) if(!vis[i]){ int temp = i; while(!vis[temp]){ vis[temp] = 1; vec[tot].push_back(temp); temp = a[temp]; } tot++; } while(scanf("%d", &m) == 1 && m){ //這裡面m表示置換的次數 getchar(); gets(s+1); int len = strlen(s+1); for(int i = len+1; i <= n; i++) s[i] = ' '; //注意在後面加空格 s[n+1] = '\0'; //不要忘了字串結束符 char ss[maxn]; for(int i = 0; i < tot; i++){ //這裡進行轉換 int len = vec[i].size(); for(int j = 0; j < len; j++) ss[vec[i][(j+m)%len]] = s[vec[i][j]]; } ss[n+1] = '\0'; printf("%s\n", ss+1); } printf("\n"); } return 0;}