您的位置:首页 > 其它

HDU-1863- 畅通工程(最小生成树,prim)

2017-07-02 15:32 387 查看
题目链接

题意:裸的最小生成树

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<time.h>
#include<set>
#include<stack>
#include<vector>
#include<map>

#define pi acos(-1)
#define maxn 111111
#define maxm 11111
#define INF 0x3F3F3F3F
#define eps 1e-8

#define pb push_back

#define mem(a) memset(a,0,sizeof a)

using namespace std;

const long long mod = 1000000007;
/**lyc**/
int n, m;
int mp[222][222];
int vis[222];
int cost[222];
void init(void) {
memset(mp, INF, sizeof mp);
for (int i = 0; i <= 111; i++) {
mp[i][i] = 0;
}
memset(vis, 0, sizeof vis);
memset(cost, INF, sizeof cost);
}
int Prim() {
cost[1] = 0;
vis[1] = 1;
int ans = 0;
for (int i = 2; i <= n; i++) {
cost[i] = mp[1][i];
}
for (int i = 1; i < n; i++) {
int minx = INF;
int pos = 0;
/**找离集合最近的点**/
for (int j = 1; j <= n; j++) {
if (!vis[j] && cost[j] < minx) {
minx = cost[j];
pos = j;
}
}
//cout << pos << endl;
if (pos == 0) {
return -1;
}
ans += cost[pos];
vis[pos] = 1;
/**加入并修改**/
for (int j = 1; j <= n; j++) {
if (!vis[j] &&  mp[pos][j] < cost[j]) {
//这里注意,已经把pos点给加入了,所以直接算,不用加原来的了
cost[j] = mp[pos][j];
}
}

}
return ans;
}
int main() {
while (scanf("%d%d", &m, &n) && (m != 0)) {
init();
int a, b, x;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &a, &b, &x);
mp[a][b] = mp[b][a] = x;
}
//cout << "***" << endl;
int ans = Prim();
if (ans == -1) {
printf("?\n");
}
else {
printf("%d\n", ans);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息