Description
The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has no public highways. So the traffic is difficult in Flatopia. The Flatopian government is aware of this problem. They’re planning to build some highways so that it will be possible to drive between any pair of towns without leaving the highway system.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 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.
Output
You should output a line contains an integer, which is the length of the longest road to be built such that all the villages are connected, and this value is minimum.
This problem contains multiple test cases!
The first line of a multiple input is an integer T, then a blank line followed by T input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of T output blocks. There is a blank line between output blocks.
Sample Input
13
0 990 692
990 0 179
692 179 0
Sample Output
692
题目的意思是某个岛国要规划高速公路,使得高速公路的总长度最小,并输出两地间最长的那条高速公里的长度。
很显然,这道题考查的就是最小生成树。这个岛国可以看成一个图,村庄为顶点,它们之间的距离就是边的权重。要使高速公路总长度最小,即使所有村庄在连通情况下的总权重最小。
最小生成树有两种算法:Prim, kruskal算法。
因为Prim的时间复杂度与边无关,所以为避免超时,使用Prim算法解此题比较保险。
有一篇不错的文章:
最小生成树Prim算法理解
以下是我的代码:
# include <iostream>
# define MAX 502
# define INFINITE 0x7fffffff
using namespace std;
int Graph[MAX][MAX];
int N;
void Prim() {
int lowcost[N]; // 存储最短边, lowcost[i] 的 i表示终点
int max_road = 0; // 用来存储最长高速公路
for (int i = 0; i < N; i++) { // 初始化
lowcost[i] = Graph[0][i];
}
for (int i = 1; i < N; i++) {
int _min = INFINITE; // 注意,_min要放在第一层for循环内在每次循环开始时更新
int flag = 0;
for (int j = 1; j < N; j++) { // 取最短边
if (lowcost[j] != 0 && lowcost[j] < _min) {
_min = lowcost[j];
flag = j;
}
}
if (_min > max_road) {
max_road = _min;
}
for (int j = 1; j < N; j++) { // 更新lowcost
if (lowcost[j] > Graph[flag][j]) {
lowcost[j] = Graph[flag][j];
}
}
}
cout << max_road << endl;
}
int main(void) {
int T;
cin >> T;
while(T--) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
Graph[i][j] = 0;
}
}
cin >> N;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> Graph[i][j];
}
}
Prim();
if (T) cout << endl;
}
return 0;
}
以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!