标签:tor pen and ini eve blog cte gif 算法
Kruskal:适用稀疏图
需要Union_Find_Set(并查集)
class Kruskal {
#define Kruskal_MAXN 100
#define Kruskal_MAXM 10005
public:
Union_Find_Set ufs;
int x[Kruskal_MAXM], y[Kruskal_MAXM], w[Kruskal_MAXM], N, M;
Kruskal() {
N = 0;
M = 0;
}
void clear() {
N = 0;
M = 0;
}
void addEdge(int a, int b, int c) {
x[M] = a;
y[M] = b;
w[M] = c;
M++;
x[M] = b;
y[M] = a;
w[M] = c;
M++;
}
void sort(int l, int r) {
int i = l, j = r, m = w[(l + r) >> 1], t;
do {
while (w[i] < m) {
i++;
}
while (m < w[j]) {
j--;
}
if (i <= j) {
t = x[i];
x[i] = x[j];
x[j] = t;
t = y[i];
y[i] = y[j];
y[j] = t;
t = w[i];
w[i] = w[j];
w[j] = t;
i++;
j--;
}
} while (i <= j);
if (l < j) {
sort(l, j);
}
if (i < r) {
sort(i, r);
}
}
int MST() {
sort(0, M - 1);
ufs.clear(N + 1);
int cnt = 0, ret = 0;
for (int i = 0; i < M; i++) {
if (cnt == N - 1) {
return ret;
}
if (ufs.getFather(x[i]) != ufs.getFather(y[i])) {
ufs.merge(x[i], y[i]);
ret += w[i];
cnt++;
}
}
if (cnt == N - 1) {
return ret;
} else {
return -1;
}
}
};
Kruskal_MAXN:最大点数
Kruskal_MAXM:最大边数
N:点数
void addEdge(int a, int b, int c):添加一条ab之间长度为c的边
int MST():最小生成树
prim:适用稠密图(暂无)
线性随机算法(暂无)
标签:tor pen and ini eve blog cte gif 算法
原文地址:http://www.cnblogs.com/dramstadt/p/6207017.html