1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include<cstdio> #include<algorithm> #define N 200001 using namespace std;
struct Road { int u, v, w; bool operator<(const Road& a){ return w < a.w; } }road[N];
int p[N]; inline void Union(int a, int b); inline int find(int a); int kruskal(int n, int e); int main() { int n, m;
while (scanf("%d%d", &n, &m) && n) { int cost = 0, i;
for (i = 0; i < m; i++) { scanf("%d%d%d", &road[i].u, &road[i].v, &road[i].w); cost += road[i].w; }
printf("%d\n", cost - kruskal(n, m)); }
return 0; } int kruskal(int n, int e) { int i, now, cost = 0; for (i = 0; i < n; i++) p[i] = i;
sort(road, road + e);
for (i = 0, now = 0; i < e&&now < n - 1; i++, now++) { while (find(road[i].u) == find(road[i].v)) i++; Union(road[i].u, road[i].v); cost += road[i].w; }
return cost; } void Union(int a, int b) { p[find(a)] = find(b); } int find(int a) { return a == p[a] ? a : (p[a] = find(p[a])); }
|