#include<iostream> #include<queue> #include<vector> usingnamespacestd; structedge { int start,end,dist; edge(int s = 0, int e = 0, int d = 0){ start = s; end = e; dist = d;} booloperator < (const edge &e) const { return dist > e.dist;}//用于实现优先级的比较函数,默认是functional中的less<T> }; intmain() { int n, m;//顶点个数n和边数m cin >> n >> m; int** a = newint*[n]; bool* label = newbool[n]; priority_queue<edge> q; for (int i = 0; i < n; i++) { label[i] = 0; a[i] = newint[n]; } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = 100; label[0] = true; int x, y, d; for (int i = 0; i < m; i++) { cin >> x >> y >> d; a[x - 1][y - 1] = d; a[y - 1][x - 1] = d; if (x == 1 || y == 1) { int k = x > y ? x : y; q.push(edge(0, k - 1, d));//以0为起点 } } int res = 0; edge e; int v = 0;//加入的顶点数 while (!q.empty()&&v<n-1) { e = q.top(); q.pop(); if (label[e.end])continue; res += e.dist; label[e.end] = true; ++v; for (int i = 0; i < n; i++){ if (a[e.end][i] < 100&&!label[i]) q.push(edge(e.end, i, a[e.end][i])); } } cout << res << endl; return0; }