洗牌问题
设2n张牌分别标记为1, 2, ..., n, n+1, ..., 2n,初始时这2n张牌按其标号从小到大排列。经一次洗牌后,原来的排列顺序变成n+1, 1, n+2, 2, ..., 2n, n。即前n张牌被放到偶数位置2, 4, ..., 2n,而后n张牌被放到奇数位置1, 3, ..., 2n-1。可以证明对于任何一个自然数n,经过若干次洗牌后可恢复初始状态。现在你的的任务是计算对于给定的n的值(n≤10^5),最少需要经过多少次洗牌可恢复到初始状态。
Input 输入数据由多组数据组成。每组数据仅有一个整数,表示n的值。 Output 对于每组数据,输出仅一行包含一个整数,即最少洗牌次数。 Sample Input 10 Sample Output 6
思路:找规律;
找数字1的位置变换;
int main() { int n; while(~scanf("%d",&n)) { int j=2,num=1; if(n==0) { printf("1\n"); continue; } while(j!=1) { if(j<=n) j*=2; else j=(j-n)*2-1; num++; } printf("%d\n",num); } return 0; }
Little A has became fascinated with the game Dota recently, but he is not a good player. In all the modes, the rdsp Mode is popular on online, in this mode, little A always loses games if he gets strange heroes, because, the heroes are distributed randomly.
Little A wants to win the game, so he cracks the code of the rdsp mode with his talent on programming. The following description is about the rdsp mode:
There are N heroes in the game, and they all have a unique number between 1 and N. At the beginning of game, all heroes will be sorted by the number in ascending order. So, all heroes form a sequence One.
These heroes will be operated by the following stages M times:
1.Get out the heroes in odd position of sequence One to form a new sequence Two;
2.Let the remaining heroes in even position to form a new sequence Three;
3.Add the sequence Two to the back of sequence Three to form a new sequence One.
After M times' operation, the X heroes in the front of new sequence One will be chosen to be Little A's heroes. The problem for you is to tell little A the numbers of his heroes.
输入 There are several test cases. Each case contains three integers N (1<=N<1,000,000), M (1<=M<100,000,000), X(1<=X<=20). Proceed to the end of file. 输出 For each test case, output X integers indicate the number of heroes. There is a space between two numbers. The output of one test case occupied exactly one line. 样例输入 5 1 2 5 2 2 样例输出 2 4 4 3 提示 In case two: N=5,M=2,X=2,the initial sequence One is 1,2,3,4,5.After the first operation, the sequence One is 2,4,1,3,5. After the second operation, the sequence One is 4,3,2,1,5.So,output 4 3. 来源 辽宁省赛2010 思路:两道问题都是找规律; 代码: #include<cstdio> #include<cstring> #include<algorithm> #include<cstdlib> #include<queue> #include<stack> #include<iostream> #include<cmath> using namespace std; typedef long long ll; typedef pair<int,int> P; const int inf=1e9-1; const int maxn=1000010; int a[maxn]; int main() { int n,m,x; while(~scanf("%d%d%d",&n,&m,&x)) { // cout<<n<<" "<<m<<" "<<x<<endl; if(n%2==0) n++; int xx=1,yy=1,k=0; while(1) { if(xx*2<=n) //规律 xx=2*xx; else xx=xx*2-n; k++; if(xx==yy) break; // cout<<x<<" "<<y<<endl; } // cout<<k<<endl; // cout<<"done1"<<endl; m=m%k; for(int i=1;i<=n;i++) a[i]=i; for(int i=1;i<=x;i++) //m已经被k约的足够小,暴力解决; { for(int j=0;j<m;j++) { if(a[i]*2<=n) a[i]=a[i]*2; else a[i]=a[i]*2-n; } printf("%d",a[i]); if(i!=x) printf(" "); } cout<<endl; // cout<<"done2"<<endl; } return 0; }