这两天搞dp搞的快暴了,想学学网络流。拿过算导来一看,最短路还没整完呢。写了一个用并查集优化的kruskal算法,并查集是用非递归的状态压缩实现的。
详见:http://www.cnblogs.com/vongang/archive/2011/07/31/2122763.html。
kruskal没有用堆优化,不是我不想,而是实在不会。。。所以直接用sort按权值排了下序,时间复杂度O(n+n*logn)
My Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1000;
struct EDG {
int v;
int u;
int w;
}edg[N];
int parent[N];
bool cmp(EDG a, EDG b) {
return a.w < b.w;
}
void set() {
for(int i = 0; i < N; i++)
parent[i] = i;
}
int find_set(int n){
int k, i, r = n;
while(parent[r] != r) {
r = parent[r];
}
k = n;
while(k != r) {
i = parent[k];
parent[k] = r;
k = i;
}
return r;
}
int kruskal(int n) {
int i, x, y, sum, cnt = 0;
set();
for(sum = 0, i = 0; i < n && cnt < n-1; i++) {
x = find_set(edg[i].u);
y = find_set(edg[i].v);
if(x == y) continue;
parent[x] = parent[y]; ++cnt;
sum += edg[i].w;
}
return sum;
}
int main() {
//freopen("data.in", "r", stdin);
int n, m, i, u, v, w;
cin >> m >> n;
for(i = 0; i < n; i++) {
scanf("%d%d%d", &u, &v, &w);
edg[i].v = v;
edg[i].u = u;
edg[i].w = w;
}
sort(edg, edg+n, cmp);
cout << kruskal(n) << endl;
return 0;
}
附一组数据:
5 6
1 2 1
2 3 3
3 4 2
1 5 2
1 4 6
2 5 4
sum = 8