思路:要计算周期,不然会超时。
#include <iostream>
#include <stdio.h>
using namespace std;
int a[202];
int main(){
int n;
int k;
int same;
cin >> n;
while(n != 0){
for(int i = 0; i < n; i++){
cin >> a[i];
}
same = 0;
// int atmp[n];
int atmp = 1;
int round[n];
for(int i = 0; i < n; i++){
round[i] = 0;
}
// for(int i = 0; i < n; i++){
// atmp[i] = a[i];
// }
for(int i = 0; i < n; i++){
atmp = a[i];
while(1){
atmp = a[atmp-1];
round[i]++;
if(atmp == a[i])
break;
//cout<<atmp;
}
}
// for(int i = 0; i < n; i++)
// cout<<round[i]<<" ";
// cout<<endl;
cin >> k;
int pos;
char text[n+1];
char textTemp[n+1];
while(k != 0){
for(int i = 0; i < n; i++) text[i] = ' ';
text[n] = '\0';
pos = 0;
getchar();
text[0] = getchar();
while(text[pos] != '\n'){
pos++;
text[pos] = getchar();
}
text[pos] = ' ';
// while(k != 0){
int ttmp;
for(int i = 0; i < n; i++){
int kkk = k%round[i];
ttmp = i+1;
// kkk--;
while(kkk>0){
ttmp = a[ttmp-1];
kkk--;
// cout<<kkk<<endl;
}
textTemp[ttmp-1] = text[i];
}
// k--;
for(int i = 0; i < n; i++){
text[i] = textTemp[i];
}
// }
for(int i = 0; i < n; i++){
cout << text[i];
}
// cout<<text;
cout << endl;
cin >> k;
}
cout << endl;
cin >> n;
}
}
参考:
http://www.cnblogs.com/ns517/archive/2009/03/04/1402951.html
http://blog.youkuaiyun.com/jw72jw/article/details/5810120
http://www.cppblog.com/csu-yx-2013/archive/2011/11/10/159934.html