于 2024-03-25 21:46:32 发布
update:2024-08-02,内容:更改排版,以及调整了码风
传送门:P3366 【模板】最小生成树
prim算法找最小生成树
定义数组部分
const int INF = 0x3f3f3f3f;
const int N = 5005;
int dis[N][N], d[N];
bool vis[N]; //用于记录是否访问过这个节点
prime核心代码部分 :
int Prim(int v0) {
int sum = 0; // 权值
for (int i = 1; i <= n; i++)
d[i] = dis[v0][i];
vis[v0] = true;
d[v0] = 0;
for (int i = 1; i < n; i++) {
int minn = INF, pos = 0;
for (int j = 1; j <= n; j++)
if (minn > d[j] && !vis[j]) {
minn = d[j];
pos = j;
}
vis[pos] = true;
sum += d[pos];
for (int j = 1; j <= n; j++) // 往回找
if (dis[pos][j] < d[j] && !vis[j])
d[j] = dis[pos][j];
}
return sum;
}
输入部分:
void solve() {
cin >> n >> m;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
dis[i][j] = INF;
int a, b, c;
for (int i = 1; i <= m; i++) {
cin >> a >> b >> c;
if (c < dis[a][b])
dis[b][a] = dis[a][b] = c;
}
int res = Prim(1);
for (int i = 1; i <= n; i++)
if (!vis[i]) {
cout << "orz";
return 0;
}
cout << res;
}