线段树合并
Orz w_yqts
在dalao指导下AC了…Orz
WA的原因可能是
在merge中如果a,b都是叶子会无法统计
#include <bits/stdc++.h>
using namespace std;
#define N 2333333
inline int read()
{
char ch=getchar();
int x=0,f=1;
while ('0'>ch || ch>'9') {if (ch=='-') f=-1;ch=getchar();}
while ('0'<=ch && ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return x*f;
}
inline void put(int x)
{
int num=0;
char c[31];
if (x<0) {putchar('-');x=-x;}
while(x) c[++num]=(x%10)+48,x/=10;
while(num) putchar(c[num--]);
putchar('\n');
}
struct node
{
int x,y,t,id;
}a[N];
int f[N],s[N],tr[N],ans[N],h[N],to[N],ls[N],rs[N];
int n,m,Q;
bool cmp(node x,node y)
{
if (x.t!=y.t) return x.t<y.t;
return x.id<y.id;
}
inline int find(int x)
{
if (f[x]==x) return x;
return f[x]=find(f[x]);
}
int tottr,rt[N];
void ins(int &k,int l,int r,int x)
{
if (!k) k=++tottr;
++tr[k];
if (l==r) return;
int mid=(l+r)>>1;
if (x<=mid) ins(ls[k],l,mid,x);else ins(rs[k],mid+1,r,x);
}
int query(int k,int l,int r,int t)
{
if (l==r) return l;
int mid=(l+r)>>1,tot=tr[ls[k]];
if (t<=tot) return query(ls[k],l,mid,t);
return query(rs[k],mid+1,r,t-tot);
}
inline int merge(int a,int b)
{
if (!a) return b;
if (!b) return a;
if(!ls[a] && !rs[a] && !ls[b] && !rs[b])
{
tr[a]=tr[a]+tr[b];
return a;
}
ls[a]=merge(ls[a],ls[b]);
rs[a]=merge(rs[a],rs[b]);
tr[a]=tr[ls[a]]+tr[rs[a]];
return a;
}
int main()
{
cin>>n>>m>>Q;
for (int i=1;i<=n;++i) a[i].t=read(),a[i].id=i,f[i]=i,s[i]=1;
sort(a+1,a+1+n,cmp);
int t=0;
for (int i=1;i<=n;++i)
{
if (a[i].t!=a[i-1].t || i==1) ++t;
h[a[i].id]=t;to[t]=a[i].t;
}
//for (int i=1;i<=n;++i) cout<<h[i]<<' ';cout<<endl;for (int i=1;i<=n;++i) cout<<to[i]<<' ';cout<<endl;
for (int i=1;i<=n;++i) ins(rt[i],1,n,h[i]);
for (int i=1;i<=m;++i) a[i].x=read(),a[i].y=read(),a[i].t=read(),a[i].id=i;
for (int i=m+1;i<=m+Q;++i) a[i].x=read(),a[i].t=read(),a[i].y=read(),a[i].id=i;
sort(a+1,a+1+m+Q,cmp);
//for (int i=1;i<=m+Q;++i) cout<<a[i].x<<' '<<a[i].y<<' '<<a[i].t<<' '<<a[i].id<<endl;
//cout<<"m="<<m<<endl;
for (int i=1;i<=m+Q;++i)
{
int x,y;
//cout<<"i="<<i<<' '<<a[i].id<<endl;
if (a[i].id<=m)
{
x=find(a[i].x),y=find(a[i].y);
if (x==y) continue;
f[y]=x;
s[x]+=s[y];
rt[x]=merge(rt[x],rt[y]);
//for (int i=1;i<=n;++i) cout<<find(i)<<' ';cout<<endl;for (int i=1;i<=n;++i) cout<<s[i]<<' ';cout<<endl;
continue;
}
x=find(a[i].x);
if (s[x]<a[i].y) {ans[a[i].id-m]=-1;continue;}
ans[a[i].id-m]=to[query(rt[x],1,n,s[x]-a[i].y+1)];
}
for (int i=1;i<=Q;++i) put(ans[i]);
}