您的位置:首页 > 编程语言 > C语言/C++

湘潭市赛 Josephus Problem 线段树

2017-06-14 08:37 288 查看
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<iostream>
#include<stdio.h>
using namespace std;
#define N 100005

int re
;
int q
;
int sum[1000005];

void build(int l,int r,int root){///建立线段树

sum[root]=r-l+1;
if(l == r) return ;  //终止条件
int m = (l+r)/2;
//向左递归 区间
build(l,m,root*2);
//向右递归 区间
build(m+1,r,root*2+1);
}
int update(int p,int l,int r,int root){///更新单个节点

sum[root]--;  //对于root总人数减少1
if(l == r) return l ;
int m = (l + r)/2;
if(p <= sum[root*2])
return    update(p,l,m,root*2);   //进入左子树
else
return   update(p-sum[root*2],m+1,r,root*2+1);  //进入右子树

}

int main()
{
int x,A,B,M,n,m;
while(scanf("%d%d%d%d%d%d",&n,&m,&x,&A,&B,&M)==6)
{
build(1,n,1);
int   s=1;
for(int i = 1; i <= n; i++)
{
s = ((int)x+s)%sum[1];  //s为要删除的位置
if(s == 0) s = sum[1];  //从头开始
int result= update(s,1,n,1);  // 更新节点并返回 位置s的数据
re[i] = result;
x = (int)(((long long )x * A + B) % M);
}
for(int i= 1; i <= m; i++)
scanf("%d",&q[i]);

for(int i=1;i<m;i++)
printf("%d ",re[q[i]]);
if(m!=0) printf("%d",re[q[m]]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线段树 C++STL