http://ac.jobdu.com/problem.php?pid=1024 并查集+贪心
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; #define MAXN 105 typedef struct Edge{ int start; int end; int weight; } Edge ; Edge edge[MAXN]; int father[MAXN]; int n, m ; int findParent (int t){ return father[t] == t ? t : father[t] = findParent(father[t]); } int Union(int x, int y){ int xParent = findParent(x); int yParent = findParent(y); if (xParent == yParent) return 0; xParent > yParent ? father[xParent] = yParent : father[yParent] = xParent; return 1; } int compare (const void * p, const void * q){ Edge * p1 = (Edge *)p; Edge * q1 = (Edge *)q; return p1->weight - q1->weight; } void setInit(){ for (int i = 1; i <= m; ++ i){ father[i] = i; } } int solution(){ int used = 0 ,re = 0; for(int i = 0;i < n - 1;i++){ if(used == m -1 )break; if (Union(edge[i].start, edge[i].end)){ used++; re += edge[i].weight; } } return used != m - 1? 0 : re; } int main() { //freopen("in.txt","r",stdin); while(cin >> n >> m){ if(n == 0)break; for(int f = 0; f < n; f ++) cin >> edge[f].start >> edge[f].end >> edge[f].weight; qsort(edge, n, sizeof(Edge), compare); setInit(); int re = solution() ; re ?cout << re <<endl : cout << '?' <<endl; } return 0; }