连通图

来源:互联网 发布:八爪鱼采集器导出数据 编辑:程序博客网 时间:2024/05/20 12:21

http://icpc.ahu.edu.cn/OJ/Problem.aspx?id=528

并查集:

  1. makeSet(s):建立一个新的并查集,其中包含 s 个单元素集合。
  2. unionSet(x, y):把元素 x 和元素 y 所在的集合合并,要求 x 和 y 所在的集合不相交,如果相交则不合并。
  3. find(x):找到元素 x 所在的集合的代表,该操作也可以用于判断两个元素是否位于同一个集合,只要将它们各自的代表比较一下就可以了。



#include <cstdio>#include <cstring>#include <cstdlib>#include <string>#include <map>#include <cmath>#include <iostream>#include <stdexcept>#include <cstddef>#include <algorithm>#include <vector>#include <numeric>#include <cctype>#define LL long long#define Endl endl#define INF 0x7fffffff//#define WJusing namespace std;int father[1010],n;int rank[1010];int Find(int x){if(x!=father[x]) father[x]=Find(father[x]);return father[x];}void Union(int x,int y){if((x=Find(x))==(y=Find(y))) return ;n--;if(rank[x]>rank[y]) father[y]=x;else {father[x]=y;if(rank[x]==rank[y]) rank[y]++;}}int main(int argc, char *argv[]){#ifdef WJ//freopen("in.txt","r",stdin);freopen("out.txt","w",stdout);#endifint m,s,t;for(int i=1;i<1010;i++)father[i]=i;memset(rank,0,sizeof(rank));scanf("%d%d",&n,&m);while(m--){scanf("%d%d",&s,&t);Union(s,t);}printf("%d\n",n-1);return 0;}


0 0