hdu 4259 置换入门题

来源:互联网 发布:python bt文件下载 编辑:程序博客网 时间:2024/06/05 13:33

Double Dealing

Time Limit: 50000/20000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2090    Accepted Submission(s): 750


Problem Description
Take a deck of n unique cards. Deal the entire deck out tok players in the usual way: the top card to player 1, the next to player 2, thekth to player k, the k+1st to player 1, and so on. Then pick up the cards – place player 1′s cards on top, then player 2, and so on, so that playerk’s cards are on the bottom. Each player’s cards are in reverse order – the last card that they were dealt is on the top, and the first on the bottom.
How many times, including the first, must this process be repeated before the deck is back in its original order?
 

Input
There will be multiple test cases in the input. Each case will consist of a single line with two integers,n and k (1≤n≤800, 1≤k≤800). The input will end with a line with two 0s.
 

Output
For each test case in the input, print a single integer, indicating the number of deals required to return the deck to its original order. Output each integer on its own line, with no extra spaces, and no blank lines between answers. All possible inputs yield answers which will fit in a signed 64-bit integer.
 

Sample Input
1 310 352 40 0
 

Sample Output
1413


题意:

n 个号码,k个运动员,循环按照顺序给运动员分发号码

例如  10  3:

第一次操作得到

A: 1 4 7 10

B: 2 5 8

C:3 6 9

然后整合这个序列得到  10  7  4  1  8  5  2  9  6  3     ---------(1)

然后再经过三次这样到操作又可以得到  1 2 3 4 5 6 7 8 9 10

我们很容易发现从   (1)号序列就可以得到   1->10->3->4->1

和四次操作的循环结果一样,然后理解发现确实可以这样做


最后我们只需要求解所有这样循环的循环节的长度求一个最大公约数即可

同过这个可以理解置换的底层含义了

注意这在不断求最大公约数的时候需要用到 long long


#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define LL long longint a[1005],vis[1005];LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}int main(){int n,k,p,cnt;freopen("in.txt","r",stdin);while(scanf("%d%d",&n,&k)!=EOF){p=1;if(n==0&&k==0) break;if(n<k){ puts("1"); continue; }for(int i=1;i<=n&&i<=k;i++)for(int j=(n-i)/k*k+i;j>0;j-=k)a[p++]=j;LL ans=1;memset(vis,0,sizeof(vis));for(int i=1;i<=n;i++){if(vis[i]) continue;p=i,cnt=0;do{vis[p]=1;p=a[p];cnt++;}while(p!=i);ans=ans/gcd(ans,cnt)*cnt;}printf("%lld\n",ans);}return 0;}


原创粉丝点击