并查集

来源:互联网 发布:韩国冒险岛 数据库 编辑:程序博客网 时间:2024/06/07 00:03

Problem Description
Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.

 

Input
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.

 

Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.

 

Sample Input
2
5 3
1 2
2 3
4 5

5 1
2 5
 

Sample Output
2
4

  其中的find函数是用来压缩路径的:

            

relation函数使用来建立关系的,讲起认识的圈起来,并通过find压缩路径找到头目

#include<iostream> using namespace std; int relation[1010];//定义关系数组   int find(int x)   //查找关系       {      if(relation[x]==x)  return x;  //没有其他关系,就返回自己         else          return (relation[x]=find(relation[x]));  //有关系的话,返回通过圈子,最终认识的头目       } void unite(int x,int y)   {   int a,b;     a=find(x);    //找到a的关系圈   b=find(y);    //找到b的关系圈     relation[a]=b; //是关系圈在建立关系圈    }  int main()    {    int T;    int m,n;    int a,b;    int i,j;    int sum;      cin>>T;      while(T--)        {        cin>>n>>m;   //输入人数和关系   for(i=1;i<=n;i++)      relation[i]=i;  //  没有找到关系之前,先定义自己和自己有关系   for(j=1;j<=m;j++)  //输入关系,进行关系联系       {      cin>>a>>b;       unite(a,b);      }       sum=0;    for(j=1;j<=n;j++)   if(relation[j]==j)   sum++;        cout<<sum<<endl;        }    return 0;    } 

 

hdu  畅通工程也是一样,现将各个村的联通关系圈起来,之后压缩路径找到father

 

#include<stdio.h>  int p[1010];     int find(int x)      {      if(p[x]==x)        return x;       else         return (p[x]=find(p[x]));      }  void Union( int x,int y)    {    int a,b;      a=find(x);      b=find(y);       p[a]=b;    }     int main()    {    int n,m;        int i,j;        int a,b;        int sum;      while(scanf("%d%d",&n,&m),n)        {        for(i=1;i<=n;i++)          p[i]=i;        for(i=1;i<=m;i++)          {          scanf("%d%d",&a,&b);             Union(a,b);          }          sum=-1;        for(j=1;j<=n;j++)          if(p[j]==j)  sum++;        printf("%d\n",sum);        }     return 0;    }



 

0 0
原创粉丝点击