POJ-2485 Highways 最小生成树
一道简单的最小生成数,求使得所有的路连通的最小总路程代价中的最长的子路的长度。
代码如下:
#include <cstring> #include <cstdlib> #include <cstdio> #include <algorithm> using namespace std; int N, pos, set[505]; struct Node { int x, y, dist; bool operator < (Node t) const { return dist < t.dist; } }e[250005]; int find(int x) { return set[x] = x == set[x] ? x : find(set[x]); } void merge(int a, int b) { set[a] = b; } int main() { int T, c, cnt; scanf("%d", &T); while (T--) { pos = cnt = 0; scanf("%d", &N); for (int i = 1; i <= N; ++i) { set[i] = i; for (int j = 1; j <= N; ++j) { scanf("%d", &c); ++pos; e[pos].x = i, e[pos].y = j, e[pos].dist = c; } } sort(e+1, e+1+pos); for (int i = 1; i <= pos; ++i) { int a = find(e[i].x), b = find(e[i].y); if (a != b) { merge(a, b); ++cnt; if (cnt == N-1) { printf("%d\n", e[i].dist); break; } } } } return 0; }