# (最小生成树 Prim算法) HDU 1863 畅通工程

Problem Description

Input

Output

Sample Input
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100

Sample Output
3
?

C++代码：
#include<iostream>
#include<algorithm>
#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,M;
while(cin>>N>>M){
if(N == 0) break;
for(int i = 1; i <= M; i++){
for(int j = 1; j <= M; j++){
mp[i][j] = INF;
}
}
int a,b,c;
for(int i = 1; i <= N; i++){
cin>>a>>b>>c;
if(c < mp[a][b])
mp[a][b] = mp[b][a] = c;  //需要注意无向图的多重边的情况，选取其中最小的权就行。
}
Prim(M,1,mp);
int sum = 0;
bool flag = true;  //判断，判断是否构成了一个生成树。
for(int i = 1; i <= M; i++){
if(lowcost[i] == INF){
flag = false;
}
sum += lowcost[i];
}
if(!flag)
cout<<"?"<<endl;
else
cout<<sum<<endl;
}
return 0;
}

posted @ 2019-05-21 09:58  PJCK  阅读(101)  评论(0编辑  收藏  举报