[HNOI2012]永无乡
Code1
权值线段树天然支持merge,线段树上二分求第k小
#include<bits/stdc++.h>using namespace std;
using ll=long long;
template <class T=int> T rd()
{T res=0;T fg=1;char ch=getchar();while(!isdigit(ch)) {if(ch=='-') fg=-1;ch=getchar();}while( isdigit(ch)) res=(res<<1)+(res<<3)+(ch^48),ch=getchar();return res*fg;
}
const ll mod=998244353;
const int N=100010;
struct node
{int l,r;int v;
}tree[N*40];
int rt[N],cnt;
int n,m;
void insert(int &u,int l,int r,int x)
{if(!u) u=++cnt;tree[u].v++;if(l==r) return;int mid=l+r>>1;if(x<=mid) insert(tree[u].l,l,mid,x);else insert(tree[u].r,mid+1,r,x);
}
int fa[N],id[N];
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
int merge(int u,int v)
{if(!u||!v) return u+v;tree[u].v+=tree[v].v;tree[u].l=merge(tree[u].l,tree[v].l);tree[u].r=merge(tree[u].r,tree[v].r);return u;}
int query(int u,int l,int r,int k)
{if(l==r) return id[l];int mid=l+r>>1;if(tree[tree[u].l].v<k) return query(tree[u].r,mid+1,r,k-tree[tree[u].l].v);return query(tree[u].l,l,mid,k);
}
int main()
{n=rd(),m=rd();for(int i=1;i<=n;i++){int x=rd();id[x]=i;insert(rt[i],1,n,x);}for(int i=1;i<=n;i++) fa[i]=i;while(m--){int u=rd(),v=rd();u=find(u),v=find(v);if(u==v) continue;fa[v]=u;rt[u]=merge(rt[u],rt[v]);}int qc=rd();while(qc--){char op[4];scanf("%s",op);int x=rd(),y=rd();if(op[0]=='Q') {int u=rt[find(x)];if(tree[u].v<y) puts("-1");else printf("%d\n",query(u,1,n,y));}else{int u=find(x),v=find(y);if(u==v) continue;fa[v]=u;rt[u]=merge(rt[u],rt[v]);}}return 0;
}
Code2
维护n课平衡树,启发式合并暴力合并。
平衡树支持第k小
pd_ds
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template<typename T>
using ordered_set = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;template <class T=int> T rd()
{T res=0;T fg=1;char ch=getchar();while(!isdigit(ch)) {if(ch=='-') fg=-1;ch=getchar();}while( isdigit(ch)) res=(res<<1)+(res<<3)+(ch^48),ch=getchar();return res*fg;
}const int N=500010;
int fa[N];
int n,m;
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
ordered_set<pair<int,int>> rt[N];
void merge(int u,int v)// u<-v
{if(rt[u].size()<rt[v].size()) swap(u,v);ordered_set<pair<int,int>>::point_iterator it=rt[v].begin();for(;it!=rt[v].end();it++) rt[u].insert(*it);rt[v].clear();fa[v]=u;
}
int main()
{n=rd(),m=rd();for(int i=1;i<=n;i++) rt[i].insert(pair<int,int>(rd(),i));for(int i=1;i<=n;i++) fa[i]=i;while(m--){int u=rd(),v=rd();u=find(u),v=find(v);if(u!=v) merge(u,v);}int qc=rd();while(qc--){char op[4];scanf("%s",op);int x=rd(),y=rd();if(op[0]=='Q') {int u=find(x);if(rt[u].size()<y) puts("-1");else printf("%d\n",rt[u].find_by_order(y-1)->second);} else{int u=find(x),v=find(y);if(u!=v) merge(u,v);}}return 0;
}