Description
Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.
Input
Output
Sample Input
4 1 2 3 4 5 6 1 6 4 1 2 3 4 5 6 7 8
Sample Output
4 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Maxn 333333
int count[Maxn]; //count为每个堆中积木个数
int under[Maxn]; //under为每个堆下面所有的积木个数
int father[Maxn]; //father为原来1 2 3 4 。。。n的积木堆的父节点
int N;
void init ()
{
int i;
for(i=0;i<=N;i++)
{
count[i]=1;
under[i]=0;
father[i]=i;
}
}
int find(int x)//在结尾find(i)时,更新每个叶节点的权值和父节点的值,而Union调用时也可以执行,然而在Union调用时只是单纯调用根节点,因此仍未对叶节点进行操作。
{
if(x!=father[x])
{
int tmp;
tmp=find(father[x]);
under[x]+=under[father[x]];
father[x]=tmp;
}
return father[x];
}
void Union(int x,int y)//合并树。合并树根的过程。而其中的叶的权值和父节点均未发生改变
{
int root1=find(x);
int root2=find(y);
if(root1!=root2)
{
under[root1] = count[root2]; //将X放在Y的上方。此次并查集所建立的树为倒置的树。下端为根,及为root1。因此root1的权值(下方个数)即为Y的总和。
count[root2] += count[root1]; //root2变为了root1的根,而root2的和即为原本root2+root1的和
father[root1] = root2; //改变X堆的父节点。之前为自己或者原来的父节点。之后改变为Y堆的父节点。
}
}
int main()
{
int i,j;
int k;
char s[5];
while (scanf("%d",&N)!=EOF)
{
init();
while(N--)
{ scanf("%s",s);
if (s[0]=='M')
{
scanf("%d%d",&i,&j);
Union(i,j);
}
else
{
scanf("%d",&i);
find(i);//为什么做这步呢?是因为Union合并后,原树的子节点仍然保留原来根的值。而且权值还未改变。需要时需要重新查找
printf("%d\n",under[i]);
}
}
}
return 0;
}
第一次做带权并查集的题。。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Maxn 333333
int count[Maxn]; //count为每个堆中积木个数
int under[Maxn]; //under为每个堆下面所有的积木个数
int father[Maxn]; //father为原来1 2 3 4 。。。n的积木堆的父节点
int N;
void init ()
{
int i;
for(i=0;i<=N;i++)
{
count[i]=1;
under[i]=0;
father[i]=i;
}
}
int find(int x)//在结尾find(i)时,更新每个叶节点的权值和父节点的值,而Union调用时也可以执行,然而在Union调用时只是单纯调用根节点,因此仍未对叶节点进行操作。
{
if(x!=father[x])
{
int tmp;
tmp=find(father[x]);
under[x]+=under[father[x]];
father[x]=tmp;
}
return father[x];
}
void Union(int x,int y)//合并树。合并树根的过程。而其中的叶的权值和父节点均未发生改变
{
int root1=find(x);
int root2=find(y);
if(root1!=root2)
{
under[root1] = count[root2]; //将X放在Y的上方。此次并查集所建立的树为倒置的树。下端为根,及为root1。因此root1的权值(下方个数)即为Y的总和。
count[root2] += count[root1]; //root2变为了root1的根,而root2的和即为原本root2+root1的和
father[root1] = root2; //改变X堆的父节点。之前为自己或者原来的父节点。之后改变为Y堆的父节点。
}
}
int main()
{
int i,j;
int k;
char s[5];
while (scanf("%d",&N)!=EOF)
{
init();
while(N--)
{ scanf("%s",s);
if (s[0]=='M')
{
scanf("%d%d",&i,&j);
Union(i,j);
}
else
{
scanf("%d",&i);
find(i);//为什么做这步呢?是因为Union合并后,原树的子节点仍然保留原来根的值。而且权值还未改变。需要时需要重新查找
printf("%d\n",under[i]);
}
}
}
return 0;
}