并查集
来源:互联网 发布:韩国冒险岛 数据库 编辑:程序博客网 时间: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; }
- HDU3938 并查集 并查集
- 并查集(集并查)
- HDU1232 并查集<并>
- 并查集
- 数据结构-并查集
- 并查集
- 并查集!
- 并查集
- 并查集
- 并查集
- 并查集
- 并查集总结
- 并查集学习
- 并查集
- 并查集
- 并查集
- 所谓并查集
- 并查集
- 关于static ,const 的一些小回顾
- 给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个
- javascript设置和获取cookie的方法
- php实现动态修改配置文件
- 【Leetcode长征系列】Valid Palindrome
- 并查集
- HttpURLConnection超时处理
- 使用MediaPlayer出现The surface has been released 异常处理方法,附代码
- hdu 1232 畅通工程
- extern用法详解(转)
- Windows 2008 无法建域控 提示没有管理员密码
- Win7下Apploc的正确安装姿势
- Arduino 编程语言手册(简单版)
- python2.7.6比python2.7.3升级过程中import module问题及解决方法