POJ 題目2985 The k-th Largest Group(線段樹單點更新求第k大值,並查集)
Time Limit: 2000MS | Memory Limit: 131072K |
Total Submissions: 7869 | Accepted: 2534 |
Description
Newman likes playing with cats. He possesses lots of cats in his home. Because the number of cats is really huge, Newman wants to group some of the cats. To do that, he first offers a number to each of the cat (1, 2, 3, …, n
Input
1st line: Two numbers N and M (1 ≤ N, M ≤ 200,000), namely the number of cats and the number of operations.
2nd to (m + 1)-th line: In each line, there is number C specifying the kind of operation Newman wants to do. If C = 0, then there are two numbers i and j (1 ≤ i, j ≤ n) following indicating Newman wants to combine the group containing the two cats (in case these two cats are in the same group, just do nothing); If C
Output
For every operation “1” in the input, output one number per line, specifying the size of the kth largest group.
Sample Input
10 10 0 1 2 1 4 0 3 4 1 2 0 5 6 1 1 0 7 8 1 1 0 9 10 1 1
Sample Output
1 2 2 2 2
Hint
When there are three numbers 2 and 2 and 1, the 2nd largest number is 2 and the 3rd largest number is 1.
Source
題目大意:n只貓,編號1~n,m個操作,0 i j意思是把i在的組併到j,1 k的意思是求第k大組的大小
註釋的是我的思路,這個寫法是參照別人的思路,他的比我的稍微快個100來ms,
ac程式碼
#include<stdio.h>
#include<string.h>
int pre[200020],num[200020];
int node[200020<<2],n,m;
void build_tr(int l,int r,int tr)
{
if(l==1)
node[tr]=n;
else
node[tr]=0;
if(l==r)
{
/*if(l==1)
node[tr]=n;
else
node[tr]=0;*/
return;
}
int mid=(l+r)>>1;
build_tr(l,mid,tr<<1);
build_tr(mid+1,r,tr<<1|1);
// node[tr]=node[tr<<1]+node[tr<<1|1];
}
void init(int n)
{
int i;
for(i=1;i<=n;i++)
{
num[i]=1;
pre[i]=i;
}
}
int find(int x)
{
if(x==pre[x])
return x;
return pre[x]=find(pre[x]);
}
void update(int pos,int add,int l,int r,int tr)
{
node[tr]+=add;
if(l==r)
{
// node[tr]+=add;
return;
}
int mid=(l+r)>>1;
if(pos<=mid)
{
update(pos,add,l,mid,tr<<1);
}
else
update(pos,add,mid+1,r,tr<<1|1);
//node[tr]=node[tr<<1]+node[tr<<1|1];
}
int query(int k,int l,int r,int tr)
{
if(l==r)
{
return l;
}
int mid=(l+r)>>1;
if(node[tr<<1|1]>=k)
query(k,mid+1,r,tr<<1|1);
else
query(k-node[tr<<1|1],l,mid,tr<<1);
}
int main()
{
// int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
build_tr(1,n,1);
init(n);
int i;
for(i=0;i<m;i++)
{
int op;
scanf("%d",&op);
if(!op)
{
int a,b;
scanf("%d%d",&a,&b);
int fa=find(a),fb=find(b);
if(fa!=fb)
{
pre[fa]=fb;
update(num[fa],-1,1,n,1);
update(num[fb],-1,1,n,1);
update(num[fa]+num[fb],1,1,n,1);
num[fb]+=num[fa];
}
}
else
{
int a;
scanf("%d",&a);
printf("%d\n",query(a,1,n,1));
}
}
}
}