【HDU2122】Ice_cream’s world III(MST基础题)

时间:2023-03-08 20:43:57
【HDU2122】Ice_cream’s world III(MST基础题)

2坑,3次WA。

1.判断重边取小。2.自边舍去。

(个人因为vis数组忘记初始化,WA了3次,晕死!!)

 #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <numeric> #define typec int
using namespace std; const int V = ;
const typec inf = 0xffff;
int vis[V];
typec lowc[V];
int Map[V][V]; typec prim (typec cost[][V], int n) {
int i, j, p;
typec minc, res = ;
memset(vis, , sizeof(vis));
vis[] = ;
for (i = ; i < n; ++ i) lowc[i] = cost[][i];
for (i = ; i < n; ++ i) {
minc = inf; p = -;
for (j = ; j < n; ++ j) {
if ( == vis[j] && minc > lowc[j]) {
minc = lowc[j]; p = j;
}
}
if (inf == minc) return -;
res += minc; vis[p] = ;
for (j = ; j < n; ++ j) {
if ( == vis[j] && lowc[j] > cost[p][j]) {
lowc[j] = cost[p][j];
}
}
}
return res;
} int main () {
int n, road_n;
int cur = ;
while (cin >> n >> road_n) {
/*if (cur ++ != 0) {
cout << endl;
}*/
for (int i = ; i < n; ++ i) {
for (int j = ; j < n; ++ j) {
if (i == j) Map[i][j] = ;
else {
Map[i][j] = inf;
}
}
} for (int i = ; i < road_n; ++ i) {
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
if (x == y) {
continue;
}
Map[x][y] = Map[y][x] = min(Map[x][y], c);
} int ans = prim (Map, n); if (ans == -) {
cout << "impossible" << endl << endl;
} else {
cout << ans << endl << endl;
}
}
return ;
}