POJ 1721 CARDS
Alice and Bob have a set of N cards labelled with numbers 1 ... N (so that no two cards have the same label) and a shuffle machine. We assume that N is an odd integer.
The shuffle machine accepts the set of cards arranged in an
arbitrary order and performs the following operation of double shuffle :
for all positions i, 1 <= i <= N, if the card at the position i
is j and the card at the position j is k, then after the completion of
the operation of double shuffle, position i will hold the card k.
Alice and Bob play a game. Alice first writes down all the
numbers from 1 to N in some random order: a1, a2, ..., aN. Then she
arranges the cards so that the position ai holds the card numbered a
i+1, for every 1 <= i <= N-1, while the position aN holds the card numbered a1.
This way, cards are put in some order x1, x2, ..., xN, where xi is the card at the i
th position.
Now she sequentially performs S double shuffles using the
shuffle machine described above. After that, the cards are arranged in
some final order p1, p2, ..., pN which Alice reveals to Bob, together
with the number S. Bob's task is to guess the order x1, x2, ..., xN in
which Alice originally put the cards just before giving them to the
shuffle machine.
Input The first line of the input contains two integers separated by a single blank character : the odd integer N, 1 <= N <= 1000, the number of cards, and the integer S, 1 <= S <= 1000, the number of double shuffle operations.
The following N lines describe the final order of cards after all the double shuffles have been performed such that for each i, 1 <= i <= N, the (i+1) st line of the input file contains pi (the card at the position i after all double shuffles).
Output The output should contain N lines which describe the order of cards just before they were given to the shuffle machine.
For each i, 1 <= i <= N, the ith line of the output file should contain xi (the card at the position i before the double shuffles).
Sample Input
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cmath> 6 using namespace std; 7 int n,m,c[1001],a[1001],b[1001]; 8 int get_round() 9 {int cnt=0,i,flag; 10 while (1) 11 { 12 for (i=1;i<=n;i++) 13 c[i]=b[b[i]]; 14 flag=1; 15 cnt++; 16 for (i=1;i<=n;i++) 17 if (c[i]!=a[i]) 18 { 19 flag=0; 20 break; 21 } 22 if (flag) return cnt; 23 for (i=1;i<=n;i++) 24 b[i]=c[i]; 25 } 26 } 27 int main() 28 {int i,cnt; 29 cin>>n>>m; 30 for (i=1;i<=n;i++) 31 { 32 scanf("%d",&a[i]); 33 b[i]=a[i]; 34 c[i]=a[i]; 35 } 36 cnt=get_round(); 37 m%=cnt; 38 m=cnt-m; 39 while (m--) 40 { 41 for (i=1;i<=n;i++) 42 b[i]=a[a[i]]; 43 for (i=1;i<=n;i++) 44 a[i]=b[i]; 45 } 46 for (i=1;i<=n;i++) 47 printf("%d\n",a[i]); 48 }