一些概念
树:无圈无环无向图
生成树:走过所有点的树
最小生成树:在树的边有权的时候,走过的边加权和最小的生成树
最小生成树的两个算法
第一个 Kruskal
基于贪心策略,不能处理含有负权的树,又被称作加边法。
基本操作是将边权从小到大排列,将每个结点看作独立的树,每次将两颗树合并。
第二个Prim
又称加点法,每次选择代价最小的点加入,逐渐扩张到整个图。
HDU1233(畅通工程) 并查集 Kruskal
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e4 + 5;
int father[maxn];
int sum;
struct node{
int u, v, w;
}edge[maxn];
void init() {
for(int i = 0; i < maxn; i++) {
father[i] = i;
}
}
int find(int x) {
return father[x] == x ? x : find(father[x]);
}
void unionn(int x,int y,int n) {
int p1 = find(x);
int p2 = find(y);
if(p1==p2) return;
father[p1] = p2;
sum += edge[n].w;
}
bool cmp(node a, node b) {
return a.w < b.w;
}
int main() {
int N;
while(~scanf("%d",&N) ) {
if(N == 0) return 0;
else {
sum = 0;
int M = N * (N - 1) / 2;
for (int i = 0; i < M; i++) {
scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w);
}
init();
sort(edge, edge + M, cmp);
for (int i = 0; i < M; i++) {
unionn(edge[i].u, edge[i].v, i);
}
printf("%d\n",sum);
}
}
return 0;
}
POJ2485 Highways 求最小生成树中最长边
http://poj.org/problem?id=2485
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 500 + 5;
int father[maxn];
int sum;
struct node{
int u, v, w;
}edge[maxn * maxn];
void init() {
for(int i = 0; i < maxn; i++) {
father[i] = i;
}
}
int find(int x) {
return father[x] == x ? x : find(father[x]);
}
bool cmp(node a, node b) {
return a.w < b.w;
}
int main() {
int N;
int T;
while(~scanf("%d",&T)) {
while(T--) {
cin >> N;
init();
int x;
int tot=0;
for(int i = 0 ; i < N; i++) {
for(int j = 0; j < N; j++) {
scanf("%d",&x);
edge[tot].u = i;
edge[tot].v = j;
edge[tot].w = x;
tot++;
}
}
sum = 0;
int ans;
sort(edge,edge + tot,cmp);
for(int i = 0; i < tot; i++) {
int p1 = find(edge[i].u);
int p2 = find(edge[i].v);
if(p1 != p2) {
father[p1] = p2;
sum++;
}
if(sum == N - 1) {
ans = edge[i].w;
break;
}
}
printf("%d\n",ans);
}
}
return 0;
}
POJ1258
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100 + 5;
int father[maxn];
int sum;
struct node{
int u, v, w;
}edge[maxn * maxn];
void init() {
for(int i = 0; i < maxn; i++) {
father[i] = i;
}
}
int find(int x) {
return father[x] == x ? x : find(father[x]);
}
bool cmp(node a, node b) {
return a.w < b.w;
}
int main() {
int N;
while(~scanf("%d",&N)) {
init();
int x;
int tot=0;
for(int i = 0 ; i < N; i++) {
for(int j = 0; j < N; j++) {
scanf("%d",&x);
edge[tot].u = i;
edge[tot].v = j;
edge[tot].w = x;
tot++;
}
}
sum = 0;
int ans;
sort(edge,edge + tot,cmp);
for(int i = 0; i < tot; i++) {
int p1 = find(edge[i].u);
int p2 = find(edge[i].v);
if(p1 != p2) {
father[p1] = p2;
sum+=edge[i].w;
}
}
printf("%d\n",sum);
}
return 0;
}