您的位置:首页 > 其它

【BZOJ 2733】 [HNOI2012]永无乡

2017-04-26 08:15 393 查看

思路

并查集+线段树合并

时间复杂度O(nlog2n+qlogn)

代码

#include <cstdio>
#include <iostream>
#include <algorithm>
#define mid ((l+r)>>1)
using namespace std;
const int maxn = 100010;
struct node{
int val;
node *ch[2];
}pool[maxn*25], *null, *root[maxn];
int fa[maxn], sz[maxn], ct, n, m, q, v[maxn];
node *get(int val){
node *now = &pool[++ct];
now->ch[0] = now->ch[1] = null;
now->val = val;
return now;
}
void build(node *now, int l, int r, int pos){
if(l == r) return;
int wh = 0; if(pos >= mid+1) wh = 1;
now->ch[wh] = get(1);
build(now->ch[wh], wh==0?l:mid+1, wh==0?mid:r, pos);
}
void merge_tree(node *fi, node *se, int l, int r){
if(l == r) return;
if(fi->ch[0] == null) fi->ch[0] = se->ch[0];
else if(se->ch[0] != null){
fi->ch[0]->val += se->ch[0]->val;
merge_tree(fi->ch[0], se->ch[0], l, mid);
}
if(fi->ch[1] == null) fi->ch[1] = se->ch[1];
else if(se->ch[1] != null){
fi->ch[1]->val += se->ch[1]->val;
merge_tree(fi->ch[1], se->ch[1], mid+1, r);
}
}
int find(int x){return x == fa[x] ? x : fa[x] = find(fa[x]);}
void merge_fa(int x, int y){
int fx = find(x), fy = find(y);
if(fx == fy) return;
if(sz[fx] < sz[fy]) swap(fx, fy);
merge_tree(root[fx], root[fy], 1, n);
sz[fx] += sz[fy]; fa[fy] = fx;
}
void que(node *now, int l, int r, int k){
if(l == r){
if(k > now->val) printf("-1\n");
else printf("%d\n", v[l]);
return;
}
if(now->ch[0]->val >= k) que(now->ch[0], l, mid, k);
else que(now->ch[1], mid+1, r, k - now->ch[0]->val);
}
int main(){
null = pool, null->val = 0, null->ch[0] = null->ch[1] = null;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i ++) root[i] = get(0);
for(int i = 1; i <= n; i ++) fa[i] = i, sz[i] = 1;
for(int i = 1, t; i <= n; i ++){
scanf("%d", &t), v[t] = i;
build(root[i], 1, n, t);
}
for(int i = 1, x, y; i <= m; i ++){
scanf("%d%d", &x, &y);
merge_fa(x, y);
}
scanf("%d", &q);
for(int i = 1, x, y; i <= q; i ++){
char ch[5];
scanf("%s%d%d", ch+1, &x, &y);
if(ch[1] == 'Q') que(root[find(x)], 1, n, y);
else merge_fa(x, y);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: