poj2377
最大生成树,kruskal将权重取负。如果并查集的大小不等于1,则说明没有将所有的谷仓连接起来,输出-1。
#include <iostream> #include <algorithm> using namespace std; const int MAXN = 1005; const int MAXM = 20005; int n, m, a, b, c; int cost[MAXN][MAXN]; int par[MAXN]; int rank[MAXN]; struct edge { int x; int y; int cost; }es[MAXN]; bool cmp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; } void init(int n) { for(int i=0; i<n; i++) { par[i] = i; rank[i] = 0; } } int find(int x) { if(par[x] == x) return x; else return par[x] = find(par[x]); } void unite(int x, int y) { x = find(x); y = find(y); if(x == y) return; if(rank[x] < rank[y]) par[x] = y; else { par[y] = x; if(rank[x] == rank[y]) rank[x]++; } } bool same(int x, int y) { return find(x) == find(y); } int main() { scanf("%d%d", &n, &m); for(int i=0; i<m; i++) { scanf("%d%d%d", &es[i].x, &es[i].y, &es[i].cost); es[i].cost = -es[i].cost; } sort(es, es+m, cmp); init(n); int res = 0; int trees = n; for(int i=0; i<m; i++) { edge e = es[i]; if(!same(e.x, e.y)) { unite(e.x, e.y); res += e.cost; trees--; } } if(trees > 1) printf("%d\n", -1); else printf("%d\n", -res); return 0; }