prim算法 : 初始化-> 找最小值,更新 - 重复 找 n-1 次。
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");using namespace std;
const int N = 105;
const int INF = 0x7fffffff;
int cost[N][N];
int lowc[N];
bool vis[N];
int n, m;
void prim(int p) {memset(vis, false, sizeof(vis));memset(lowc, 0, sizeof(lowc));for(int i = 1; i <= p; i++) {if(cost[1][i] != -1) {lowc[i] = cost[1][i];}else lowc[i] = INF;}vis[1] = true;int sum = 0;for(int i = 1; i < p; i++) {int mini = INF, c = 0;for(int j = 1; j <= p; j++) {if(!vis[j] && lowc[j] < mini) {mini = lowc[j];c = j;}}sum += mini;vis[c] = true;for(int j = 1; j <= p; j++) {if(!vis[j] && cost[c][j] != -1 && cost[c][j] < lowc[j]) {lowc[j] = cost[c][j];}}}cout << sum << endl;
}
int main() {while(cin >> n, n) {cin >> m;memset(cost, -1, sizeof(cost));int a, b, c;for(int i = 0; i < m; i++) {cin >> a >> b >> c;if((cost[a][b] != -1 && c < cost[a][b]) || cost[a][b] == -1) {cost[a][b] = cost[b][a] = c;}}prim(n);}return 0;
}