Portal: Josephus problem
Test instructions: The classic Joseph Problem, there are n individuals, each time a number to the K-person out, to ask for the rest of the last person.
Analysis: Using the segment tree to simulate the Joseph problem, recording the reduction of the interval, and then according to each number of people in the interval row, the segment tree log (n) found and updated, the total complexity of O (Nlog (n)).
#include <cstdio>#include<cstring>#include<cmath>#include<algorithm>#defineN 100010#defineMoD 1000000007#defineLL Long Long#defineLson l,m,rt<<1#defineRson m+1,r,rt<<1|1using namespacestd;intn,k;intsum[n<<2],vis[n];voidPushup (intRT) { intls=rt<<1, rs=ls|1; SUM[RT]=sum[ls]+Sum[rs];}voidBuildintLintRintRT) { if(l==R) {Sum[rt]=1;return; } intM= (l+r) >>1; Build (Lson); Build (Rson); Pushup (RT);}voidUpdateintNumintLintRintRT) { if(l==R) {Vis[l]=1; SUM[RT]=0; return; } intM= (l+r) >>1; if(num<=sum[rt<<1]) update (Num,lson); ElseUpdate (num-sum[rt<<1],rson); Pushup (RT);}intMain () {intt,cas=1; scanf ("%d",&T); while(t--) {scanf ("%d%d",&n,&k); memset (Vis,0,sizeof(VIS)); Build (1N1); intnum=1; for(intI=n;i>1; i--) {num= (num+k-1)%i; if(num==0) num=i; Update (NUM,1N1); } for(intI=1; i<=n;i++) if(!Vis[i]) {printf ("Case %d:%d\n", cas++,i); Break; } }}View Code
Lightoj 1179 (segment tree)