POJ 2485 Highways
Description
Flatopian towns are numbered from 1 to N. Each highway connects exactly two towns. All highways follow straight lines. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways.
The Flatopian government wants to minimize the length of the longest highway to be built. However, they want to guarantee that every town is highway-reachable from every other town.
Input
The first line of each case is an integer N (3 <= N <= 500), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 65536]) between village i and village j. There is an empty line after each test case.
Output
Sample Input
1 3 0 990 692 990 0 179 692 179 0
Sample Output
692
Hint
Source
Solution
求最小生成樹上的最大邊,裸題,Prim或Kruscal都可以Code
Prim
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <map>
#include <vector>
#include <queue>
#define inf 65537
#define L 510
#define LL long long
using namespace std;
int T, n, d[L][L], a[L], ans, minx, temp;
bool vis[L];
int main() {
freopen("2485.in", "r", stdin);
freopen("2485.out", "w", stdout);
scanf("%d", &T);
while (T--) {
memset(d, 65537, sizeof(d));
memset(vis, false, sizeof(vis));
memset(a, 0, sizeof(a));
scanf("%d", &n);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
scanf("%d", &d[i][j]);
if (i == j) d[i][j] = 65537;
}
for (int i = 1; i < n; ++i) a[i] = d[0][i];
ans = 0, vis[0] = true;
for (int i = 1; i < n; ++i) {
minx = 65537;
for (int j = 0; j < n; ++j)
if (!vis[j] && a[j] < minx) minx = a[j], temp = j;
vis[temp] = true, ans = max(minx, ans);
for (int j = 0; j < n; ++j)
if (!vis[j] && d[j][temp] < a[j]) a[j] = d[j][temp];
}
printf("%d\n", ans);
}
return 0;
}
Kruscal#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <map>
#include <vector>
#include <queue>
#define inf 65537
#define L 510
#define LL long long
using namespace std;
struct node {
int x, y, d;
} e[L * L];
int T, n, fa[L], cnt, dis, ans, tot;
inline bool comp(node a, node b) {
return a.d < b.d;
}
inline int findfa(int x) {
if (x != fa[x]) return fa[x] = findfa(fa[x]);
return x;
}
int main() {
freopen("2485.in", "r", stdin);
freopen("2485.out", "w", stdout);
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
cnt = 0;
for (int i = 0; i < n; ++i) {
fa[i] = i;
for (int j = 0; j < n; ++j) {
scanf("%d", &dis);
if (i > j) e[cnt].x = i, e[cnt].y = j, e[cnt++].d = dis;
}
}
sort(e, e + cnt, comp);
ans = tot = 0;
for(int i = 0; i < cnt; ++i) {
int a = findfa(e[i].x);
int b = findfa(e[i].y);
if (a != b) {
fa[a] = b;
ans = max(ans, e[i].d);
}
}
printf("%d\n", ans);
}
return 0;
}