标签:
Description
Input
Output
Sample Input
3 0 990 692 990 0 179 692 179 0 1 1 2
Sample Output
179
#include <iostream> #include <cstdio> #include <string> #include <queue> #include <vector> #include <map> #include <algorithm> #include <cstring> #include <cctype> #include <cstdlib> #include <cmath> #include <ctime> using namespace std; const int SIZE = 105; int N,M,NUM; int FATHER[SIZE]; struct Node { int from,to,cost; }G[SIZE * SIZE]; void ini(void); int find_father(int); void unite(int,int); bool same(int,int); bool comp(const Node &,const Node &); int kruskal(void); int main(void) { int from,to,cost; while(scanf("%d",&N) != EOF) { ini(); for(int i = 1;i <= N;i ++) for(int j = 1;j <= N;j ++) { scanf("%d",&cost); if(i == j) continue; if(i < j) { G[NUM].from = i; G[NUM].to = j; G[NUM].cost = cost; NUM ++; } } scanf("%d",&M); while(M --) { scanf("%d%d",&from,&to); unite(from,to); } sort(G,G + NUM,comp); printf("%d\n",kruskal()); } return 0; } void ini(void) { NUM = 0; for(int i = 1;i <= N;i ++) FATHER[i] = i; } int find_father(int n) { if(n == FATHER[n]) return n; return FATHER[n] = find_father(FATHER[n]); } void unite(int x,int y) { x = find_father(x); y = find_father(y); if(x == y) return ; FATHER[x] = y; } bool same(int x,int y) { return find_father(x) == find_father(y); } bool comp(const Node & a,const Node & b) { return a.cost < b.cost; } int kruskal(void) { int ans = 0,count = 0; for(int i = 0;i < NUM;i ++) if(!same(G[i].from,G[i].to)) { unite(G[i].from,G[i].to); ans += G[i].cost; count ++; if(count == N - 1) break; } return ans; }
POJ 2421 Constructing Roads (最小生成树)
标签:
原文地址:http://www.cnblogs.com/xz816111/p/4547669.html