1. 程式人生 > >Two permutations CodeForces - 323C

Two permutations CodeForces - 323C

http://codeforces.com/problemset/problem/323/C

主席樹裸題 對於第i個版本的線段樹 a[i]在b序列中什麼位置出現 就在那個位置加一

 

 

#include <bits/stdc++.h>
using namespace std;
const int maxn=2e6+10;

struct node
{
    int l,r,val;
};

node tree[20*maxn];
int ary[maxn],pos[maxn],root[maxn];
int n,q,num;

int build(int l,int r)
{
    int cur,m;
    cur=num++;
    tree[cur].l=tree[cur].r=tree[cur].val=0;
    if(l==r) return cur;
    m=(l+r)/2;
    tree[cur].l=build(l,m);
    tree[cur].r=build(m+1,r);
    return cur;
}

int update(int rot,int tar,int l,int r)
{
    int cur,m;
    cur=num++;
    tree[cur]=tree[rot];
    tree[cur].val++;
    if(l==r) return cur;
    m=(l+r)/2;
    if(tar<=m) tree[cur].l=update(tree[rot].l,tar,l,m);
    else tree[cur].r=update(tree[rot].r,tar,m+1,r);
    return cur;
}

int query(int lrot,int rrot,int pl,int pr,int l,int r)
{
    int res,m;
    if(pl<=l&&r<=pr) return tree[rrot].val-tree[lrot].val;
    res=0,m=(l+r)/2;
    if(pl<=m) res+=query(tree[lrot].l,tree[rrot].l,pl,pr,l,m);
    if(pr>m) res+=query(tree[lrot].r,tree[rrot].r,pl,pr,m+1,r);
    return res;
}

int main()
{
    int i,tmp,ans,l1,r1,l2,r2;
    scanf("%d",&n);
    for(i=1;i<=n;i++) scanf("%d",&ary[i]);
    for(i=1;i<=n;i++){
        scanf("%d",&tmp);
        pos[tmp]=i;
    }
    root[0]=build(1,n);
    for(i=1;i<=n;i++){
        root[i]=update(root[i-1],pos[ary[i]],1,n);
    }
    scanf("%d",&q);
    ans=0;
    while(q--){
        scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
        l1=(l1-1+ans)%n+1,r1=(r1-1+ans)%n+1,l2=(l2-1+ans)%n+1,r2=(r2-1+ans)%n+1;
        if(l1>r1) swap(l1,r1);
        if(l2>r2) swap(l2,r2);
        ans=query(root[l1-1],root[r1],l2,r2,1,n);
        printf("%d\n",ans);
        ans++;
    }
    return 0;
}