Title Description
There are n children numbered from 1 to N playing an out-of-the-loop game. At the beginning, n children in a circle, numbered i+1 children standing on the left of the number I children. The child numbered 1 stands on the left of the child numbered n. The first number of children numbered 1 began to count off, and then stood on the left side of the children in sequence, until a number to a number m out of the circle. Until there are only 1 children left, the game is complete.
Now given the n,m, ask N children to make a circle of the order.
input
The only row contains two integer n,m. (1<=n,m<=30000)
Output
The only row contains n integers, separated by a space for each of the two integers, and the first integer denotes the number of the child who circled the first I.
Sample Input
5 3
Sample output
3 1 5) 2 4
A good question to think about is to find out the rank of the person who needs to be out of the circle, and then output and delete.
But what if n is 30000?
The problem is the line tree, but the line tree can not be deleted, too cumbersome.
So I thought of treap.
The code is a bit long, but well understood.
It should be noted that although RN is the last ranking, this time the first person's ranking should be the same as RN, because one has been reduced.
Therefore, the initial value of Rn is 1.
1#include <cstdio>2#include <cstdlib>3#include <algorithm>4 using namespacestd;5 intl[30001], r[30001], num[30001], si[30001], rnd[30001], tot, root;6 voidPushup (intk)7 {8SI[K] = Si[l[k]] + si[r[k]] +1;9 }Ten voidZigint&k) One { A intt =L[k]; -L[K] =R[t]; -R[T] =K; theSI[T] =Si[k]; - Pushup (k); -K =T; - } + voidZagint&k) - { + intt =R[k]; AR[K] =L[t]; atL[T] =K; -SI[T] =Si[k]; - Pushup (k); -K =T; - } - voidInsint&k,intx) in { - if(!k) to { +K = + +tot; -NUM[K] =x; theSI[K] =1; *RND[K] =rand (); $ return;Panax Notoginseng } -SI[K] + + ; the if(X <Num[k]) + { A ins (l[k], x); the if(Rnd[l[k]) <Rnd[k]) + Zig (k); - } $ Else $ { - ins (r[k], x); - if(Rnd[r[k]) <Rnd[k]) the Zag (k); - }Wuyi } the voidDelint&k,intx) - { Wu if(!k)return; - if(x = =Num[k]) About { $ if(L[k] * r[k] = =0) -K = L[k] +R[k]; - Else if(Rnd[l[k]) <Rnd[r[k]]) - Zig (k), Del (k, x); A Else + Zag (k), Del (k, x); the } - Else if(X <Num[k]) $SI[K]--, Del (L[k], x); the Else theSI[K]--, Del (R[k], x); the } the intGetRank (intKintx) - { in if(x = = Num[k])returnSI[L[X]] +1; the Else if(x < num[k])returnGetRank (L[k], x); the Else returnGetRank (R[k], x) + si[l[x]] +1; About } the intFindintKintx) the { the if(x <= si[l[k])returnfind (L[k], x); + Else if(x > Si[l[k]] +1)returnFind (R[k], x-si[l[k]]-1); - Else returnNum[k]; the }Bayi intMain () the { the intN, M, I, RN =1, C; -scanf"%d%d", &n, &m); - for(i =1; I <= N; i + + ) the ins (root, i); the for(i =1; I <= N; i + + ) the { theRN = (rn + M-2+ si[root])% si[root] +1; -c =find (root, RN); theprintf"%d", c); the del (root, c); the }94printf"\ n"); the return 0; the}
"codevs1282" Joseph question