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?

输入

There are multiple test cases.

The first line of each test cases contains six integers 2 ≤ n ≤ 100000, 0 ≤ m ≤ 100000, 0 ≤ x[1], A, B < M ≤ 100000. The second line contains m integers 1 ≤ q[i] < n.

输出

For each test case, output a line containing m integers, the people executed in the q[i]-th round.

样例输入

2 1 0 1 2 3
1
41 5 1 1 0 2
1 2 3 4 40

样例输出

1
2 4 6 8 35
 
#include<algorithm>
#include<cstdio> 
#include<iostream>
using namespace std;
typedef long long LL;
#define maxn 200005
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
LL sum[4*maxn],a[maxn],c[maxn];///一般线段树sum[]开4*n为保守空间大小,这里开小了就可能会报错
void build(LL l,LL r,LL rt)   ///建线段树
{
    sum[rt]=r-l+1;
    LL m=(l+r)>>1;
    if(l==r)
        return;
    build(lson); ///建左树
    build(rson); ///建右树
} 
int update(LL l,LL r,LL rt,LL num) ///单个结点的更新
{ 
    sum[rt]--;///一人出队后包含该结点的区间都减一
    LL m=(l+r)/2; 
    if(l==r) return l;
    LL t; 
    if(num<=sum[rt<<1]) ///左区间的对应结点的更新
        t=update(lson,num); 
    else          ///右区间的对应结点的更新
        t=update(rson,num-sum[rt<<1]); 
    return t; 
} 
int main() 
{ 
    LL n,m,A,B,M,x,i;
    while(~scanf("%lld%lld%lld%lld%lld%lld",&n,&m,&x,&A,&B,&M)) 
    { 
        for(i=0; i<m; i++) 
            scanf("%lld",&c[i]); 
        build(1,n,1); 
        LL ans=1; 
        for(i=1; i<=n; i++) 
        {
            if(i!=1) 
                x=(x*A+B)%M;     ///按题中所给的x[i]得到的式子
            ans=(ans+x)%sum[1];   ///ans是要删除的位置,sum[1]为当前总人数
            if(ans==0) ans=sum[1]; ///从第一个重新开始
            a[i]=update(1,n,1,ans); ///更新结点返回ans对应的位置
        } 
        for(i=0; i<m-1; i++) 
            printf("%lld ",a[c[i]]); 
        if(m) 
            printf("%lld",a[c[m-1]]); 
        printf("\n");
    } 
    return 0; 
} 

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值