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);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值