题目地址:http://ac.jobdu.com/problem.php?pid=1024
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
3 ?
#include <stdio.h> #include <stdlib.h> typedef struct node{ int start; int end; int weight; }Node; int father[101]; int rank[101]; void Make_Set (int M){ int i; for (i=1; i<=M; ++i){ father[i] = i; rank[i] = 0; } } int Find_Set (int x){ if (x != father[x]){ father[x] = Find_Set (father[x]); } return father[x]; } int Union (int x, int y){ x = Find_Set (x); y = Find_Set (y); if (x == y) return 0; if (rank[x] > rank[y]){ father[y] = x; rank[x] += rank[y]; } else{ if (rank[x] == rank[y]) ++rank[y]; father[x] = y; } return 1; } int compare (const void * p, const void * q){ Node * p1 = (Node *)p; Node * q1 = (Node *)q; return p1->weight - q1->weight; } int main(void){ int N, M; Node road[5000]; int i; int cnt; int ans; while (scanf ("%d%d", &N, &M) != EOF){ if (N == 0) break; //scanf ("%d", &M); for (i=0; i<N; ++i){ scanf ("%d%d%d", &road[i].start, &road[i].end, &road[i].weight); } qsort (road, N, sizeof(Node), compare); Make_Set (M); ans = 0; cnt = 0; for (i=0; i<N; ++i){ if (cnt == M - 1) break; if (Union (road[i].start, road[i].end)){ ++cnt; ans += road[i].weight; } } if (cnt == M - 1){ printf ("%d\n", ans); } else{ printf ("?\n"); } } return 0; }
九度OJ上相似的题目:http://ac.jobdu.com/problem.php?pid=1347,CODE代码片