P2755 solution to a problem [problem] shuffle

This is the first solution to my problem

Please forgive a lot

The questions do not actually use the array

Let's look at the case n = 3:

Original:
123 456

4 1 5 2 6 3

2 4 6 1 3 5

1 2 3 4 5 6

We went to the observation position 2

The first position: 2

Second position: 4

Third position: 1

Because 2 is the first half of the card stack, so you can directly by 2, so we found 4 is a multiple of 2

Since the latter half stack card 4, it is found that it corresponds to the foregoing first card --4-3, then find its location (4-3) * 2, and in front of rear card is the card which corresponds position -1, therefore, it is (4-3) 2-1 *, we count was found to be 1, is indeed the correct answer, so my approach is right

We do this program

I used to simulate, to come to such a formula

if(i>n)i=(i-n)*2-1;//如果它在后半堆,找到它对应的前面的牌,算出它对应的前面的牌的位置,再-1
else i=i*2;//如果它在前半堆,直接乘以2

So AC code

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n,i=1,s=0;//只要第1张牌回到了初始位,整付牌就回到了初始状态
    cin>>n;//读入
    do{
    	if(i>n)i=(i-n)*2-1;//如果它在后半堆,找到它对应的前面的牌,算出它对应的前面的牌的位置,再-1
    	else i=i*2;//如果它在前半堆,直接乘以2
		s++;
	}while(i!=1);
	cout<<s;
    return 0;
}
Published 41 original articles · won praise 61 · views 617

Guess you like

Origin blog.csdn.net/qq_46230164/article/details/105318593