题目:53. 寻宝(第七期模拟笔试) (kamacoder.com)
最小生成树-prim算法
#include<bits/stdc++.h>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n + 1, vector<int>(n + 1, 10001));
while(m--) {
int x, y;
cin >> x >> y;
cin >> grid[x][y];
grid[y][x] = grid[x][y];
}
vector<int> minDist(n + 1, 10001);
vector<bool> isTree(n + 1, false);
int cur = 1;
for(int i = 0;i < n;i++) {
int min = 10001;
for(int j = 1;j <= n;j++) {
if(!isTree[j] && minDist[j] < min) {
min = minDist[j];
cur = j;
}
}
isTree[cur] = true;
for(int j = 1;j <= n;j++) {
if(!isTree[j] && grid[cur][j] < minDist[j]) {
minDist[j] = grid[cur][j];
}
}
}
int result = 0;
for(int i = 2;i <= n;i++) {
result += minDist[i];
}
cout << result << endl;
return 0;
}
最小生成树-Kruskal 算法
#include<bits/stdc++.h>
using namespace std;
int n = 10001;
vector<int> father(10001, 0);
struct edge{
int l, r, val;
};
void init() {
for(int i = 1;i <= n;i++) {
father[i] = i;
}
}
int find(int x) {
return x == father[x] ? x : father[x] = find(father[x]);
}
void join (int u, int v) {
u = find(u);
v = find(v);
if(u == v) return;
father[v] = u;
}
int main(){
int m;
cin >> n >> m;
vector<edge> edges;
while(m--) {
int l, r, val;
cin >> l >> r >> val;
edges.push_back({l, r, val});
}
sort(edges.begin(), edges.end(), [](const edge& a, const edge& b){return a.val < b.val;});
init();
int result = 0;
for(int i = 0;i < edges.size();i++) {
if(find(edges[i].l) == find(edges[i].r)) continue;
else {
result += edges[i].val;
join(edges[i].l, edges[i].r);
}
}
cout << result << endl;
}