图论 - 数论 - 生成树
题目链接:https://www.luogu.org/problem/P3366
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
const int M = 200010;
int n, m, dis[N], ans;
int tot, head[N], val[M << 1], nxt[M << 1] ,to[M << 1];
bool vis[N];
void add(int x, int y, int z) {
to[ ++ tot] = y;
val[tot] = z;
nxt[tot] = head[x];
head[x] = tot;
}
void Prim() {
memset(dis, 0x3f, sizeof dis);
memset(vis, 0, sizeof vis);
dis[1] = 0;
for (int i = 1; i <= n; i ++ ) {
int tmp = 1 << 30, k;
for (int j = 1; j <= n; j ++ ) {
if (vis[j] == 0 && dis[j] < tmp) {
tmp = dis[j];
k = j;
}
}
vis[k] = 1;
ans += dis[k];
for (int j = head[k]; j; j = nxt[j]) {
if (vis[to[j]] == 0 && dis[to[j]] > val[j]) {
dis[to[j]] = val[j];
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i ++ ) {
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
add(x, y, z);
add(y, x, z);
}
Prim();
printf("%d\n", ans);
return 0;
}
原文地址:https://www.cnblogs.com/littleseven777/p/11857174.html
时间: 2024-10-10 05:37:59