hdu_5919_Sequence II(主席樹)

來源:互聯網
上載者:User

標籤:code   str   print   c++   splay   題目   names   href   cat   

題目連結:hdu_5919_Sequence II

題意:

給你n個數,m個詢問,每次問你一個區間中每一種數在區間中第一次出現的位置的中位元,強制線上。

題解:

一看就是主席樹搞,不過這裡要詢問第一次出現的位置,有個技巧就是倒著將數插進去,如果有相同的數,就把位置靠後的數的貢獻取消掉,這樣查詢的時候就只需要查詢root[l]了,因為root[l]包括了l到n的資訊,前面已經只保留了相同數的最前面的位置,所以查詢一共有多少種數時直接查詢root[l]的l到r就行了。

 1 #include<bits/stdc++.h> 2 #define F(i,a,b) for(int i=a;i<=b;i++) 3 using namespace std; 4  5 const int N=2e5+7; 6 struct node{int l,r,sum;}T[40*N]; 7  8 int t,n,m,a[N],pre[N],root[N],tot,ic=1; 9 10 void update(int &x,int y,int pos,int val,int l=1,int r=n)11 {12     T[++tot]=x?T[x]:T[y],T[tot].sum+=val,x=tot;13     if(l==r)return;14     int m=l+r>>1;15     if(pos<=m)update(T[x].l,T[y].l,pos,val,l,m);16     else update(T[x].r,T[y].r,pos,val,m+1,r);17 }18 19 int query(int x,int k,int l=1,int r=n)20 {21     if(l==r)return l;22     int m=l+r>>1;23     if(k<=T[T[x].l].sum)return query(T[x].l,k,l,m);24     return query(T[x].r,k-T[T[x].l].sum,m+1,r);25 }26 27 int getsum(int x,int L,int R,int l=1,int r=n)28 {29     if(L<=l&&r<=R)return T[x].sum;30     int m=l+r>>1,ans=0;31     if(L<=m)ans+=getsum(T[x].l,L,R,l,m);32     if(R>m)ans+=getsum(T[x].r,L,R,m+1,r);33     return ans;34 }35 36 int main()37 {38     scanf("%d",&t);39     while(t--)40     {41         printf("Case #%d: ",ic++);42         scanf("%d%d",&n,&m);43         tot=0;44         F(i,1,n)scanf("%d",a+i);45         for(int i=n;i>0;i--)46         {47             if(pre[a[i]])update(root[i],root[i+1],pre[a[i]],-1);48             update(root[i],root[i+1],i,1);49             pre[a[i]]=i;50         }51         int ans=0,l,r,sum;52         F(i,1,m)53         {54             scanf("%d%d",&l,&r);55             l=(l+ans)%n+1,r=(r+ans)%n+1;56             if(l>r)l^=r,r^=l,l^=r;57             sum=getsum(root[l],l,r);58             printf("%d%c",ans=query(root[l],sum+1>>1)," \n"[i==m]);59         }60         while(tot)T[tot].l=T[tot].r=T[tot].sum=0,tot--;61         F(i,1,n)root[i]=0,pre[a[i]]=0;62     }63     return 0;64 }
View Code

 

hdu_5919_Sequence II(主席樹)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.