湘潭市赛 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 
#include 
using namespace std; 
#define N 100005 
  
  
int re[N]; 
int q[N]; 
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


你可能感兴趣的:(ACM_C++,STL,ACM_线段树)