兩種方式
- Prim (稠密圖)
- Kruskal(疏密圖)
Prim (稠密圖)
S:當前已經在聯通塊中的所有點的集合
1. dist[i] = INF
2. for n 次
t<-S外離S最近的點
利用t更新S外點到S的距離
st[t] = true
n次迭代之后所有點都已加入到S中
Dijkstra演算法是更新到起始點的距離,Prim是更新到集合S的距離
所以Dijkstra演算法迭代n-1次, Prim迭代n次;
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510, INF = 0x3f3f3f3f;
//和
int n, m;
int g[N][N], 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;
//尋找離集合S最近的點
if(i && dist[t] == INF) return INF;
//判斷是否連通,有無最小生成樹
if(i) res += dist[t];
st[t] = true;
//更新最新S的權值和
for(int j = 1; j <= n; j++) dist[j] = min(dist[j], g[t][j]);
}
return res;
}
int main() {
cin >> n >> m;
int u, v, w;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(i ==j) g[i][j] = 0;
else g[i][j] = INF;
while(m--) {
cin >> u >> v >> w;
g[u][v] = g[v][u] = min(g[u][v], w);
}
int t = prim();
//臨時存盤防止執行兩次函式導致最后僅回傳0
if(t == INF) puts("impossible");
else cout << t << endl;
}
Kruskal(疏密圖)
下面展示一些 行內代碼片,
思路:
1.將所有邊按照權重從小到大排序 O(mlog(m))O(mlog(m))
2.列舉每條邊(a, b, 權重c) O(m)O(m)
if a, b 兩點不連通
將a, b邊加入集合中
3.下一步和并查集一個操作
4.使用并查集,查詢兩個結點是否屬于一個集合, 合并兩個結點
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10, M = 2e5 + 10, INF = 0x3f3f3f3f;
int n, m;
int p[N];
struct Edge {
int a, b, w;
bool operator<(const Edge &e) const {
return w < e.w;
}
} es[M];
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int kruskal() {
//res記錄最小生成樹的樹邊權重之和,cnt記錄的是全部加入到樹的集合中邊的數量
int cnt = 0, res = 0;
sort(es, es + m);
for (int i = 1; i <= n; i++) p[i] = i;
for (int i = 0; i < m; i++) {
int a = es[i].a, b = es[i].b, w = es[i].w;
a = find(a), b = find(b);
if (a != b) {
p[a] = b;
res += w;
cnt++;
}
}
if (cnt != n - 1) return INF;
else return res;
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
es[i] = {a, b, w};
}
int t = kruskal();
if (t == INF) cout << "impossible";
else cout << t;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/263915.html
標籤:其他
上一篇:一篇文章足夠你學習嵌入式GUI LVGL技術,提供史上最全的LVGL技術文章總結,檔案代碼下載總結)
下一篇:wyh的物品
