Hdu1232 畅通工程 【并查集】
生活随笔
收集整理的這篇文章主要介紹了
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; }?
轉載于:https://www.cnblogs.com/aiiYuu/archive/2013/03/30/2989960.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Hdu1232 畅通工程 【并查集】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 准备写一些开发章
- 下一篇: SDUT ACM 2144 最小生成树,