这道题实际上就是一个裸的最小生成树,联系到我最近写并查集写得非常之火热,所以果断的就用了kruskal这个算法……
题目链接http://poj.org/problem?id=1861
AC代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define M 30010
#define N 1010
#define max(a, b) a > b ? a : b;
struct edage
{
int u, v, w;
bool j;
}e[M];
int p[N], tot;
int find(int x)
{
return p[x] != x ? p[x] = find(p[x]) : x;
}
void init(int x, int y, int z)
{
tot++;
e[tot].u = x;
e[tot].v = y;
e[tot].w = z;
e[tot].j = 0;
tot++;
e[tot].u = y;
e[tot].v = x;
e[tot].w = z;
e[tot].j = 0;
}
int cmp(edage a, edage b)
{
return a.w < b.w;
}
int main()
{
int n, m;
int x, y, z;
int r1, r2;
int cnt;
int maxi;
while (scanf("%d%d", &n, &m) != EOF)
{
cnt = 0; maxi = 0;
for (int i = 1; i <= n; i++)
p[i] = i;
tot = 0; memset(e, 0, sizeof(e));
while (m--)
{
scanf("%d%d%d", &x, &y, &z);
init(x, y, z);
}
sort(e + 1, e + tot + 1, cmp);
for (int i = 1; i <= tot; i++)
{
r1 = find(e[i].u); r2 = find(e[i].v);
if (r1 != r2)
{
p[r2] = r1;
cnt++;
e[i].j = 1;
maxi = max(e[i].w, maxi);
}
}
printf("%d\n%d\n", maxi, cnt);
for (int i = 1; i <= tot; i++)
{
if (e[i].j) printf("%d %d\n", e[i].u, e[i].v);
}
}
return 0;
}