John is not only a magic master but also a shuffling master.
Famous though he is, he likes interacting with his fans by playing a game with his fantastic shuffling skills.
The game shows as follows:
He first shows a deck of pokers contains NNN cards indexed 1,2,…,N1,2,\dots ,N1,2,…,N and all the cards are the same. He notes that the side contains numbers as the front side and the other side as the back. Later he selects one of his fans to choose a positive integer MMM that is not greater than 101010. After that, he will shuffle the cards purposefully and put it on the desktop. Note that at this moment the front sides of the cards are facing to the desk.
Then, the selected fans should perform the following steps until there is no card on the desk.
Place the card on the top of the piles to John's hand. If there are already some cards in his hand, put it on the top of them.
If there remain cards on the desk:
(a) Put a card from the top of the piles to the bottom of it.
(b) Execute the step (a) of M times.
© Go to step 1.
Next, it is time to witness the miracle.
John will continually overturn the cards on his hand top to bottom, and we will find that the cards are always in decreasing order.
One day, one of John’s fans, Tom, a smart JBer, understands the key to this magic. He turns to you and comments that the key to that magic is the shuffling John did previously. For any number MMM, he will turn the cards in a specific order after the shuffling. As you are not as smart as Tom, you should find the index of the KKKth cards from the top of the piles after the shuffling.
链接
我们发现原始牌的构造都是1开头,并且都是隔m个数放一个,已经放的不再计数。
用队列模拟取前(m+1)个数出队,前m个再重新入队。直到队列为空。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=4e7+10;
int n,m,k,x;
int a[maxn];
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
queue<int> q;
for(int i=2;i<=n;i++){
q.push(i);
}
a[1]=1;
int sum=2,t,tmp;
while(!q.empty()){
t=m;
while(t>=1){
tmp=q.front();
q.pop();
q.push(tmp);
t--;
}
tmp=q.front();
a[tmp]=sum++;
q.pop();
}
scanf("%d",&k);
while(k--){
scanf("%d",&x);
printf("%d\n",a[x]);
}
}
return 0;
}