解题思路:这道题并查集很容易,合并时找到父节点就直接加上去就ok了。关键是如何求K大数,我一直在想用线段树怎么写,一开始想如果直接记录数的大小那肯定是没戏了,借鉴了一下别人的思路:区间[a,b]记录的是所有的数里面,等于a,a+1,a+2,......,b-1,b的个数。看到这里就应该明白了,这里线段树的用法是把它看做是一个1-n的数轴。到时候要修改某一个数,就直接在数轴上修改它。至于记录[a,b]的个数,是为了找到K大数。
参考博客:http://blog.sina.com.cn/s/blog_6fd8e0fe0100v89n.html
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 200005;
struct Segment
{
int l,r;
int sum;
}tree[maxn<<2];
int n,m,fa[maxn],tot[maxn];
int find(int x)
{
if(fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
void build(int rt,int l,int r)
{
tree[rt].l = l, tree[rt].r = r;
if(tree[rt].l == 1) tree[rt].sum = n;
else tree[rt].sum = 0;
if(l == r) return;
int mid = (l + r) >> 1;
build(rt<<1,l,mid);
build(rt<<1|1,mid+1,r);
}
void update(int rt,int pos,int val)
{
tree[rt].sum += val;
if(tree[rt].l == tree[rt].r) return;
int mid = (tree[rt].l + tree[rt].r) >> 1;
if(pos <= mid) update(rt<<1,pos,val);
else update(rt<<1|1,pos,val);
}
int query(int rt,int k)
{
if(tree[rt].l == tree[rt].r) return tree[rt].l;
int mid = (tree[rt].l + tree[rt].r) >> 1;
if(tree[rt<<1|1].sum >= k) return query(rt<<1|1,k);
else return query(rt<<1,k - tree[rt<<1|1].sum);
}
int main()
{
int op,a,b,x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i = 1; i <= n; i++)
fa[i] = i, tot[i] = 1;
build(1,1,n);
for(int i = 1; i <= m; i++)
{
scanf("%d",&op);
if(op)
{
scanf("%d",&a);
printf("%d\n",query(1,a));
}
else
{
scanf("%d%d",&a,&b);
x = find(a);
y = find(b);
if(x == y) continue;
fa[y] = x;
update(1,tot[x],-1);
update(1,tot[y],-1);
update(1,tot[x]+tot[y],1);
tot[x] += tot[y];
tot[y] = 0;
}
}
}
return 0;
}
用树状数组求k大数:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 200005;
struct Tree
{
int n,c[maxn];
void init(int n)
{
this->n = n;
memset(c,0,sizeof(c));
}
int lowbit(int x)
{
return x & -x;
}
void update(int x,int d)
{
while(x <= n)
{
c[x] += d;
x += lowbit(x);
}
}
int sum(int x)
{
int ans = 0;
while(x > 0)
{
ans += c[x];
x -= lowbit(x);
}
return ans;
}
}tree;
int n,m,fa[maxn],cnt[maxn];
int find(int x)
{
if(fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
int main()
{
int op;
while(scanf("%d%d",&n,&m)!=EOF)
{
tree.init(n);
tree.update(1,n);
for(int i = 1; i <= n; i++) fa[i] = i,cnt[i] = 1;
while(m--)
{
scanf("%d",&op);
if(op == 0)
{
int i,j;
scanf("%d%d",&i,&j);
int f1 = find(i);
int f2 = find(j);
if(f1 != f2)
{
tree.update(cnt[f1],-1);
tree.update(cnt[f2],-1);
fa[f2] = f1;
cnt[f1] += cnt[f2];
tree.update(cnt[f1],1);
}
}
else
{
int k,l = 1,r = n,mid,ans;
scanf("%d",&k);
while(l <= r)
{
mid = (l + r) >> 1;
int tmp = tree.sum(n) - tree.sum(mid-1);
if(tmp >= k)
{
ans = mid;
l = mid + 1;
}
else r = mid - 1;
}
printf("%d\n",ans);
}
}
}
return 0;
}