Josephus Problem

Do you know the famous Josephus Problem? There are n people standing in a circle waiting to be executed. The counting out begins at the first people in the circle and proceeds around the circle in the counterclockwise direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom.

In traditional Josephus Problem, the number of people skipped in each round is fixed, so it's easy to find the people executed in the i-th round. However, in this problem, the number of people skipped in each round is generated by a pseudorandom number generator:

x[i+1] = (x[i] * A + B) % M.

Can you still find the people executed in the i-th round?

//

#include<iostream>
#include<stdio.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int wx[100001];
int an[100001];
const int maxnn=200000;
int w,sum[maxnn<<2];

void bu(int l,int r,int rt);
int up(int p,int l,int r,int rt);

int main()  {
    int n,m,i;
    int x,A,B,M;
    while(scanf("%d %d %d %d %d %d", &n, &m, &x, &A, &B, &M) != EOF)
    {
        bu(1,n,1);
        int z = 1;
        for(i = 1; i <= n; i++)
        {
            z = ((int)x+z)%sum[1];
            if(z == 0) z = sum[1];
            int s = up(z,1,n,1);
            an[i] = s;
            x = (int)(((long long int)x * A + B) % M);
        }          for(i = 0; i < m; i++)
        scanf("%d",&wx[i]);
        for(i=0;i<m-1;i++)
            printf("%d ",an[wx[i]]);
        if(m!=0)
            printf("%d",an[wx[m-1]]);
        printf("\n");      }
        return 0;
}

void bu(int l,int r,int rt) {
    sum[rt] = r - l + 1;
    if(l == r) return ;
    int m = (l+r) >> 1;
    bu(lson);
    bu(rson);
}

int up(int p,int l,int r,int rt)
{
    sum[rt]--;
    if(l == r) return l ;
    int m = (l + r) >> 1;
    if(p <= sum[rt<<1])
    return up(p,lson);
    else
        return up(p-sum[rt<<1],rson);
}


猜你喜欢

转载自blog.csdn.net/qq_39134293/article/details/80055889
今日推荐