# (最小生成树 Prim) HDU 1233 还是畅通工程

Problem Description

Input

Output

Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0

Sample Output
3
5

Hint
Huge input, scanf is recommended.

C++代码：
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 110;
const int INF = 0x3f3f3f3f;
int mp[maxn][maxn];
int lowcost[maxn];
bool vis[maxn];
void Prim(int n, int u0, int mp[maxn][maxn]){
vis[u0] = true;
for(int i = 1; i <= n; i++){
if(i != u0){
lowcost[i] = mp[u0][i];
vis[i] = false;
}
else
lowcost[i] = 0;
}
for(int i = 1; i <= n; i++){
int minn = INF,u = u0;
for(int j = 1; j <= n; j++){
if(!vis[j] && lowcost[j] < minn){
minn = lowcost[j];
u = j;
}
}
if(u == u0) break;
vis[u] = true;
for(int j = 1; j <= n; j++){
if(!vis[j] && lowcost[j] > mp[u][j])
lowcost[j] = mp[u][j];
}
}
}
int main(){
int N;
while(cin>>N){
if(N==0) break;
int M = (N*(N-1))/2;
for(int i = 1; i <= N; i++){
for(int j = 1; j <= N; j++){
mp[i][j] = INF;
}
}
int a,b,c;
for(int i = 1; i <= M; i++){
cin>>a>>b>>c;
if(c < mp[a][b]){
mp[a][b] = mp[b][a] = c;
}
}
Prim(N,1,mp);
int sum = 0;
for(int i = 1; i <= N; i++){
sum += lowcost[i];
}
cout<<sum<<endl;
}
return 0;
}

posted @ 2019-05-21 10:29  PJCK  阅读(53)  评论(0编辑  收藏