Problem Description
有n个城市,其中有些城市之间可以修建公路,修建不同的公路费用是不同的。现在我们想知道,最少花多少钱修公路可以将所有的城市连在一起,使在任意一城市出发,可以到达其他任意的城市。
Input
输入包含多组数据,格式如下。
第一行包括两个整数n m,代表城市个数和可以修建的公路个数。(n <= 100, m <=10000)
剩下m行每行3个正整数a b c,代表城市a 和城市b之间可以修建一条公路,代价为c。
Output
每组输出占一行,仅输出最小花费。
Example Input
3 2 1 2 1 1 3 1 1 0
Example Output
2 0
Hint
Author
赵利强
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e2 + 5;
const int INF = 0x3f3f3f3f;
bool vis[maxn];
int dis[maxn], Map[maxn][maxn];
void CSH() {
memset(Map, INF, sizeof(Map));
memset(vis, 0, sizeof(vis));
}
void SR(int m) {
while(m--) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if(Map[a][b] > c) {
Map[a][b] = Map[b][a] = c;
}
}
}
void Prim(int n) {
for(int i = 1; i <= n; i++) {
dis[i] = Map[1][i];
}
dis[1] = 0;
vis[1] = 1;
int sum = 0;
for(int i = 1; i < n; i++) {
int ans = INF;
int flag;
for(int j = 1; j <= n; j++) {
if(!vis[j] && dis[j] <ans) {
ans = dis[j];
flag = j;
}
}
vis[flag] = 1;
sum += ans;
for(int j = 1; j <= n; j++) {
if(!vis[j] && dis[j] > Map[flag][j]) {
dis[j] = Map[flag][j];
}
}
}
printf("%d\n", sum);
}
int main() {
int n, m;
while(~scanf("%d%d", &n, &m)) {
CSH();
SR(m);
Prim(n);
}
}
/***************************************************
User name:
Result: Accepted
Take time: 12ms
Take Memory: 244KB
Submit time: 2018-02-01 15:01:42
****************************************************/