图论——题目汇总+代码总结(五)
作者:
就是要AC
,
2021-05-16 21:07:14
,
所有人可见
,
阅读 409
Prim
AcWing 858. Prim算法求最小生成树
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 510, INF = 0x3f3f3f3f;
int n, m;
int g[N][N];
int dist[N];
bool st[N];
int prim()
{
memset(dist, 0x3f, sizeof dist);
int res = 0;
for (int i = 0; i < n; i++)
{
int t = -1;
for (int j = 1; j <= n; j++)
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
if (i && dist[t] == INF) return INF;
if (i) res += dist[t];
for (int j = 1; j <= n; j++) dist[j] = min(dist[j], g[t][j]);
//if (i) res += dist[t];
//res不能在这个位置,对于坑点数据 4 4 -10
//4这个点存在负环,当t==j的时候,min(dist[t], g[t][t])会把自己更新小了
st[t] = true; //下标容易打错
}
return res;
}
int main()
{
scanf("%d%d", &n, &m);
memset(g, 0x3f, sizeof g);
while (m--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
g[a][b] = g[b][a] = min(g[a][b], c); //无向图是一种特殊的有向图
}
int t = prim();
if (t == INF) puts("impossible");
else printf("%d\n", t);
return 0;
}