Hdu1232 畅通工程 【并查集】
http://acm.hdu.edu.cn/showproblem.php?pid=1232
题目大意:有几个集合,问最少需要连几根线才能把这些集合并为一个集合。
N个集合的话就需要N-1条路就行了,简单并查集
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <cmath> #include <queue> using namespace std; template <class T> void checkmin(T &t,T x) {if(x < t) t = x;} template <class T> void checkmax(T &t,T x) {if(x > t) t = x;} template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;} template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;} typedef pair <int,int> PII; typedef pair <double,double> PDD; typedef long long ll; #define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++) const int N = 1111; int f[N] , n , m; bool vis[N]; int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } void Union(int x,int y) { int a = find(x) , b = find(y); f[a] = f[b] = f[x] = f[y] = min(a , b); } int main() { while(~scanf("%d",&n) && n) { scanf("%d",&m); for(int i=1;i<=n;i++) f[i] = i , vis[i] = 0; while(m--) { int x , y; scanf("%d%d",&x,&y); Union(x , y); } int ans = -1; for(int i=1;i<=n;i++) { int x = find(i); if(!vis[x]) { vis[x] = 1; ans ++; } } printf("%d\n" , ans); } return 0; }