洛谷P3960 列队(NOIp2017)

版权声明:蒟蒻Blog随意转载 https://blog.csdn.net/a1799342217/article/details/82596018

线段树动态开点

题目传送门

去年不会动态开点啊。。。
建n+1棵树,前n棵维护当前这行(除了最后一列),第n+1棵维护最后一列。每次操作的时候分操作的列是不是最后一列讨论一下就好了。
细节有点多,调了好久最后还是借鉴了一下题解

代码:

#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 300005
#define F inline
using namespace std;
typedef long long LL;
struct tree{ int ls,rs,sz; LL x; }t[N<<6];
int n,m,q,mx,nd,rt[N],p[N]; LL ans,tmp;
F char readc(){
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    return l==r?EOF:*l++;
}
F int _read(){
    int x=0; char ch=readc();
    while (!isdigit(ch)) ch=readc();
    while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x;
}
F void writec(LL x){ if (x>9) writec(x/10); putchar(x%10+48); }
#define pd(l,r,f) (f==n+1?max(min(r,n)-l+1,0):max(min(r+1,m)-l,0))
F void nsrt(int &x,int l,int r,int p,LL w,int f){
    if (!x) t[x=++nd].sz=pd(l,r,f); int mid=l+r>>1;
    t[x].sz++; if (l==r) return void(t[x].x=w);
    if (p<=mid) nsrt(t[x].ls,l,mid,p,w,f);
    else nsrt(t[x].rs,mid+1,r,p,w,f);
}
F LL srch(int &x,int l,int r,int w,int f){
    if (!x) t[x=++nd].sz=pd(l,r,f); int mid=l+r>>1,p; t[x].sz--;
    if (l==r) return t[x].x?t[x].x:t[x].x=(f<=n?1ll*(f-1)*m+l:1ll*l*m);
    if (w<=(p=t[x].ls?t[t[x].ls].sz:mid-l+1))
        return srch(t[x].ls,l,mid,w,f);
    else return srch(t[x].rs,mid+1,r,w-p,f);
}
F LL calc(int x,int y){
    LL ans,tmp=srch(rt[n+1],1,mx,x,n+1);
    ans=y!=m?srch(rt[x],1,mx,y,x):tmp;
    if (y!=m) nsrt(rt[x],1,mx,++p[x],tmp,x);
    return nsrt(rt[n+1],1,mx,++p[n+1],ans,n+1),ans;
}
int main(){
    n=_read(),m=_read(),q=_read(),mx=max(n,m)+q;
    for (int i=1;i<=n+1;i++) p[i]=(i==n+1?n:m-1);
    for (int x,y;q;q--) x=_read(),y=_read(),writec(calc(x,y)),puts("");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1799342217/article/details/82596018