P3960-列队【权值线段树】
正題
題目鏈接:https://www.luogu.com.cn/problem/P3960
題目大意
n?mn*mn?m的隊(duì)列,起初站在第(i,j)(i,j)(i,j)位置的人編號(hào)是(i?1)?n+j(i-1)*n+j(i?1)?n+j。然后每次選擇一個(gè)人出隊(duì)后所有人向左補(bǔ)齊后所有人向前補(bǔ)齊,然后剛剛出列的那個(gè)人入隊(duì)。
求每次出列的人的編號(hào)。
解題思路
我們發(fā)現(xiàn)每次要補(bǔ)齊的就是出隊(duì)那一行的和最后一列的。
首先考慮如何維護(hù)最后一列,我們要求每次刪除一個(gè)數(shù)并加入一個(gè)到隊(duì)尾。用權(quán)值線段樹可以維護(hù)。
然后考慮對(duì)于每一行,我們分為兩種情況,一種是本來在隊(duì)列里的,一種是新加進(jìn)來的。新加進(jìn)來的不難維護(hù),也是每次刪除一個(gè)并且加入一個(gè)。對(duì)于原來就在隊(duì)列里的,我們顯然不能開n?mn*mn?m的線段樹,正男♂難則反,權(quán)值線段樹的權(quán)值表示這個(gè)范圍內(nèi)已經(jīng)出隊(duì)了的人數(shù)即可。
然后動(dòng)態(tài)開點(diǎn),時(shí)間復(fù)雜度O(nlog?n)O(n\log n)O(nlogn)
codecodecode
#include<cstdio> #include<cstring> #include<algorithm> #define ll long long #define p(x,y) (((x)-1)*m+(y)) using namespace std; const ll N=1e6+10; ll n,m,q,tot,rt[N],siz[N],ne[N]; struct Seq_Tree1{ll cnt,w[N<<4],ls[N<<4],rs[N<<4];ll Find(ll &x,ll l,ll r,ll val){if(!x)x=++cnt;if(l==r){w[x]++;return l;}ll mid=(l+r)>>1,ans;if(mid-w[ls[x]]>=val)ans=Find(ls[x],l,mid,val);else ans=Find(rs[x],mid+1,r,val+w[ls[x]]);w[x]=w[ls[x]]+w[rs[x]];return ans;} }T1; struct Seq_Tree2{ll cnt,w[N<<4],ls[N<<4],rs[N<<4],a[N<<4];void Insert(ll &x,ll l,ll r,ll pos,ll val){if(!x)x=++cnt;if(l==r){w[x]++;a[x]=val;return;}ll mid=(l+r)>>1;if(pos<=mid)Insert(ls[x],l,mid,pos,val);else Insert(rs[x],mid+1,r,pos,val);w[x]=w[ls[x]]+w[rs[x]];return;}ll Find(ll &x,ll l,ll r,ll val){if(!x)x=++cnt;if(l==r){w[x]--;return a[x];}ll mid=(l+r)>>1,ans;if(w[ls[x]]>=val)ans=Find(ls[x],l,mid,val);else ans=Find(rs[x],mid+1,r,val-w[ls[x]]);w[x]=w[ls[x]]+w[rs[x]];return ans;} }T2; int main() {//freopen("P3960_7.in","r",stdin);scanf("%lld%lld%lld",&n,&m,&q);tot=n;for(ll i=1;i<=n;i++)T2.Insert(rt[0],1,n+q,i,p(i,m)),siz[i]=m-1;for(ll i=1;i<=q;i++){if(i==469-10)i++,i--;ll x,y;scanf("%lld%lld",&x,&y);if(y==m){ll k=T2.Find(rt[0],1,n+q,x);printf("%lld\n",k);T2.Insert(rt[0],1,n+q,++tot,k);}else if(y<=siz[x]){ll k=T1.Find(rt[x],1,m,y);printf("%lld\n",p(x,k));ll w=T2.Find(rt[0],1,n+q,x);T2.Insert(rt[x+n],1,q,++ne[x],w);T2.Insert(rt[0],1,n+q,++tot,p(x,k));siz[x]--;}else{ll k=T2.Find(rt[x+n],1,q,y-siz[x]);printf("%lld\n",k);ll w=T2.Find(rt[0],1,n+q,x);T2.Insert(rt[x+n],1,q,++ne[x],w);T2.Insert(rt[0],1,n+q,++tot,k);}}return 0; }總結(jié)
以上是生活随笔為你收集整理的P3960-列队【权值线段树】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果官方的最大羊毛苹果 羊毛
- 下一篇: P2831-愤怒的小鸟【状压dp】