HDU5919 H - Sequence II (可持久化线段树)

problem:
给你n个数字,和m个查询.
将[l,r]之间数第一次出现的位置信息弄成一个新的数组,然后找出其中k/2大的数.(k为位置的数量)
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+100;
const int M=maxn*40;
int n,q;
int a[maxn];
int T[maxn];
int lson[M],rson[M],c[M],tot;
int build (int l,int r) {
    int root=tot++;
    c[root]=0;
    if (l!=r) {
        int mid=(l+r)>>1;
        lson[root]=build(l,mid);
        rson[root]=build(mid+1,r);
    }
    return root;
}
int up (int root,int p,int v) {
    int newRoot=tot++;
    int tmp=newRoot;
    c[newRoot]=c[root]+v;
    int l=1,r=n;
    while (l<r) {
        int mid=(l+r)>>1;
        if (p<=mid) {
            lson[newRoot]=tot++;
            rson[newRoot]=rson[root];
            newRoot=lson[newRoot];
            root=lson[root];
            r=mid;
        }
        else {
            rson[newRoot]=tot++;
            lson[newRoot]=lson[root];
            newRoot=rson[newRoot];
            root=rson[root];
            l=mid+1;
        }
        c[newRoot]=c[root]+v;
    }
    return tmp;
}
int query (int root,int l,int r,int L,int R) {
    if (l>=L&&r<=R) return c[root];
    int mid=(l+r)>>1;
    int ans=0;
    if (L<=mid) ans+=query(lson[root],l,mid,L,R);
    if (R>mid) ans+=query(rson[root],mid+1,r,L,R);
    return ans; 
}
int kth (int root,int l,int r,int k) {
    if (l==r) return l;
    int mid=(l+r)>>1;
    if (c[lson[root]]>=k) return kth(lson[root],l,mid,k);
    else return kth(rson[root],mid+1,r,k-c[lson[root]]);
}
int mp[maxn];
int main () {
    int _;
    scanf("%d",&_);
    for (int ca=1;ca<=_;ca++) {
        scanf("%d%d",&n,&q);
        for (int i=1;i<=n;i++) scanf("%d",a+i);
        tot=0;
        T[n+1]=build(1,n);
        memset(mp,0,sizeof(mp));
        for (int i=n;i;i--) {
            if (!mp[a[i]]) {
                T[i]=up(T[i+1],i,1);
            }
            else {
                int tt=up(T[i+1],mp[a[i]],-1);
                T[i]=up(tt,i,1);
            }
            mp[a[i]]=i;
        }
        vector<int> ans;
        int pre=0;
        while (q--) {
            int l,r;
            scanf("%d%d",&l,&r);
            l=(l+pre)%n+1;
            r=(r+pre)%n+1;
            if (l>r) swap(l,r);
            int k=query(T[l],1,n,1,r);
            ans.push_back(kth(T[l],1,n,(k+1)/2));
            pre=ans.back();
        }
        printf("Case #%d:",ca);
        for (int i=0;i<ans.size();i++) printf(" %d",ans[i]);
        printf("\n");
    }
}

 

posted @ 2020-11-22 13:52  zlc0405  阅读(66)  评论(0编辑  收藏  举报