您的位置:首页 > 其它

POJ 3590 The shuffle Problem

2018-02-06 20:41 330 查看
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.

Input

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).

Output

Each test case takes a line, with an integer m in the head, following the case of shuffling.
 

Sample Input
2
1
5

Sample Output
1 1
6 2 1 4 5 3

求出大的循环长度的lcm
与游戏这道题相似,我们考虑把答案lcm分解成质因数的幂
$lcm=p_1^{a_1}*p_2^{a_2}*......$
显然有$p_1^{a_1}+p_2^{a_2}+......<=n$
不足n用1补齐
因为100内素数只有25个,所以搜索就行了
由于要字典序最小,所以我们要使循环数最小
那么我们使在lcm相同情况下,使得大的素数幂数更大就行了

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int prime[31],tot,maxlcm,a[31],step[31],n,cnt,s[101];
bool vis[101];
int qpow(int x,int y)
{
int res=1;
while (y)
{
if (y&1) res=res*x;
x=x*x;
y/=2;
}
return res;
}
void dfs(int x,int re,int lcm)
{int i;
if (re<prime[x])
{
if (lcm>maxlcm)
{
memset(a,0,sizeof(a));
for (i=1;i<x;i++)
a[i]=step[i];
maxlcm=lcm;
}
return;
}
step[x]=0;
if (x+1<=tot)
dfs(x+1,re,lcm);
for (step[x]=prime[x];step[x]<=re;step[x]*=prime[x])
if (x+1<=tot)
dfs(x+1,re-step[x],lcm*step[x]);
}
int main()
{int T,i,j,p;
cin>>T;
for (i=2;i<=100;i++)
{
if (vis[i]==0)
{
tot++;
prime[tot]=i;
}
for (j=1;j<=tot;j++)
{
if (i*prime[j]>100) break;
vis[i*prime[j]]=1;
if (i%prime[j]==0) break;
}
}
while (T--)
{
cin>>n;
maxlcm=0;
dfs(1,n,1);
cnt=0;p=0;
for (i=1;i<=tot;i++)
{
if (a[i]) s[++cnt]=a[i],p+=a[i];
}
for (i=p+1;i<=n;i++)
s[++cnt]=1;
sort(s+1,s+cnt+1);
printf("%d",maxlcm);
int last=1;
for (i=1;i<=cnt;i++)
{
for (j=1;j<=s[i]-1;j++)
{
printf(" %d",last+j);
}
printf(" %d",last);
last=last+s[i];
}
cout<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: