POJ 3590 The shuffle Problem
Any case of shuffling of n cards can be described with a permutation of 1 to n. Thus there are totally n! cases of shuffling. Now suppose there are 5 cards, and a case of shuffle is <5, 3, 2, 1, 4>, then the shuffle will be:
Before shuffling:1, 2, 3, 4, 5
The 1st shuffle:5, 3, 2, 1, 4
The 2nd shuffle:4, 2, 3, 5, 1
The 3rd shuffle:1, 3, 2, 4, 5
The 4th shuffle:5, 2, 3, 1, 4
The 5th shuffle:4, 3, 2, 5, 1
The 6th shuffle:1, 2, 3, 4, 5(the same as it is in the beginning)
You'll find that after six shuffles, the cards' order returns the beginning. In fact, there is always a number m for any case of shuffling that the cards' order returns the beginning after m shuffles. Now your task is to find the shuffle with the largest m. If there is not only one, sort out the one with the smallest order.
The first line of the input is an integer T which indicates the number of test cases. Each test case occupies a line, contains an integer n (1 ≤ n ≤ 100).
Each test case takes a line, with an integer m in the head, following the case of shuffling.
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cmath> 6 using namespace std; 7 int prime[31],tot,maxlcm,a[31],step[31],n,cnt,s[101]; 8 bool vis[101]; 9 int qpow(int x,int y) 10 { 11 int res=1; 12 while (y) 13 { 14 if (y&1) res=res*x; 15 x=x*x; 16 y/=2; 17 } 18 return res; 19 } 20 void dfs(int x,int re,int lcm) 21 {int i; 22 if (re<prime[x]) 23 { 24 if (lcm>maxlcm) 25 { 26 memset(a,0,sizeof(a)); 27 for (i=1;i<x;i++) 28 a[i]=step[i]; 29 maxlcm=lcm; 30 } 31 return; 32 } 33 step[x]=0; 34 if (x+1<=tot) 35 dfs(x+1,re,lcm); 36 for (step[x]=prime[x];step[x]<=re;step[x]*=prime[x]) 37 if (x+1<=tot) 38 dfs(x+1,re-step[x],lcm*step[x]); 39 } 40 int main() 41 {int T,i,j,p; 42 cin>>T; 43 for (i=2;i<=100;i++) 44 { 45 if (vis[i]==0) 46 { 47 tot++; 48 prime[tot]=i; 49 } 50 for (j=1;j<=tot;j++) 51 { 52 if (i*prime[j]>100) break; 53 vis[i*prime[j]]=1; 54 if (i%prime[j]==0) break; 55 } 56 } 57 while (T--) 58 { 59 cin>>n; 60 maxlcm=0; 61 dfs(1,n,1); 62 cnt=0;p=0; 63 for (i=1;i<=tot;i++) 64 { 65 if (a[i]) s[++cnt]=a[i],p+=a[i]; 66 } 67 for (i=p+1;i<=n;i++) 68 s[++cnt]=1; 69 sort(s+1,s+cnt+1); 70 printf("%d",maxlcm); 71 int last=1; 72 for (i=1;i<=cnt;i++) 73 { 74 for (j=1;j<=s[i]-1;j++) 75 { 76 printf(" %d",last+j); 77 } 78 printf(" %d",last); 79 last=last+s[i]; 80 } 81 cout<<endl; 82 } 83 }