Http://acm.pku.edu.cn/JudgeOnline/problem? Id = 1026
If we directly simulate the problem based on the meaning of the question, because the range of K is not given in the question, it is possible to time out. In fact, the data in K is very large, so thisAlgorithmDoes not work.
Each operation is equivalent to a replacement of the sequence. The knowledge of the replacement group shows that the order of the replacement is KK, then, the result of K replications is the same as that of K % KK replications. Therefore, you can first find the order of the replacement group.
If the order of each element in the sequence is obtained separately, and then the minimum public multiple of all the ending elements is obtained to obtain the order of the entire replacement group, this order may be large and time-out.
In another way, due to k replacement, each element can be considered as independent, that is, after K replacement, element I will reach the PI position. Therefore, we replace each element separately, find the order KI (<= N) of each element, and then perform K % Ki replacement to find the position pI of the last I element. The time complexity of this algorithm is O (n ^ 2 ).
// Replacement Group
# Include < Stdio. h >
# Include < String . H >
CharBuf [201], Buf2 [201], Buf3 [201];
IntA [201];
Int Getm ( Int I ){
Int RET = 1 ;
Int Now = A [I] - 1 ;
While (Now ! = I ){
RET ++ ;
Now = A [now] - 1 ;
}
Return RET;
}
Int Main (){
Int N, K;
Char Space;
While (Scanf ( " % D \ n " , & N) ! = EOF && N ){
For ( Int I = 0 ; I < N; I ++ )
Scanf ( " % D " , & A [I]);
Scanf ( " \ N " );
While (Scanf ( " % D " , & K) ! = EOF ){
If (K = 0 ){
Scanf ( " \ N " );
Break ;
}
Scanf ( " % C " , & Space );
Gets (BUF );
Int Len = Strlen (BUF );
If (BUF [Len - 1 ] = ' \ R ' ) BUF [Len -- ] = 0 ;
For ( Int I = 0 ; I < N - Len; I ++ ) BUF [Len + I] = ' ' ;
Memset (buf2, 0 , Sizeof (Buf2 ));
For ( Int I = 0 ; I < N; I ++ ){
Int M = Getm (I );
Int Kk = K % M;
Int Now = I;
While (Kk -- ){
Now = A [now] - 1 ;
}
Buf2 [now] = Buf [I];
}
Printf ( " % S \ n " , Buf2 );
}
Putchar ( ' \ N ' );
}
Return 0 ;
}