MST算法

Kruskal

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define INF 0x3f3f3f3f
 4 #define M(a, b) memset(a, b, sizeof(a))
 5 const int N = 1e3 + 10, maxn = 1e4 + 10;
 6 int p[N], n, m;
 7 struct Edge {
 8     int u, v, w;
 9     bool operator < (const Edge rhs) const {
10         return w < rhs.w;
11     }
12 }e[maxn];
13 
14 int find(int u) {return u == p[u] ? u : find(p[u]);};
15 
16 int Kruskal() {
17     int ans = 0;
18     for (int i = 0; i < n; ++i) p[i] = i;
19     sort(e, e+m);
20     for (int i = 0; i < m; ++i) {
21         int u = find(e[i].u), v = find(e[i].v);
22         if (u != v) {
23             p[v] = u;
24             ans += e[i].w;
25         }
26     }
27     return ans;
28 }
View Code

 

Prim

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N = 1e4 + 5;
 4 bool vis[N];
 5 int n, m;
 6 struct Node {
 7     int v, w;
 8     bool operator < (const Node &rhs) const {
 9         return w > rhs.w;
10     }
11 };
12 vector<Node> G[N];
13 
14 int Prim() {
15     int ans = 0;
16     M(vis, 0); vis[1] = 1;
17     priority_queue<Node> q;
18     q.push(Node{1, 0});
19     int u = 1;
20     for (int k = 1; k < n; ++k) {
21         for (int i = 0; i < G[u].size(); ++i)
22             if (!vis[G[u][i].v]) q.push(G[u][i]);
23         while (!q.empty() && vis[q.top().v]) q.pop();
24         ans += q.top().w;
25         vis[q.top().v] = 1;
26         u = q.top().v;
27         q.pop();
28     }
29     return ans;
30 }
View Code

 

posted @ 2017-04-25 08:44  Robin!  阅读(686)  评论(0编辑  收藏  举报