首页 > 代码库 > POJ2485 Highways【Prim】
POJ2485 Highways【Prim】
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 of input is an integer T, which tells how many test cases followed.
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.
For each test case, 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.
Sample Input
13
0 990 692
990 0 179
692 179 0
Sample Output
692Hint
Huge input,scanf is recommended.Source
POJ Contest,Author:Mathematica@ZSU
题目大意:岛上要建高铁,有N个站点,给你一个图,表示这N个站点每个站点之间的距离,
要求建造的高铁路线能连接所有的站点,并且使总的路程最短。求出满足情况的路线中两个站
点间最长的路。
思路:根据要求求出最小生成树,并求出最小生成树上的最大边,就是最终答案。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; int Map[550][550],low[550],vis[550]; void Prim(int N) { int MAX = 0; memset(vis,0,sizeof(vis)); int pos = 1; int ans = 0; vis[1] = 1; for(int i = 1; i <= N; ++i) if(i != pos) low[i] = Map[pos][i]; for(int i = 1; i < N; ++i) { int Min = 0xffffff0; for(int j = 1; j <= N; ++j) { if(!vis[j] && Min > low[j]) { pos = j; Min = low[j]; } } vis[pos] = 1; ans += Min; if(MAX < Min) MAX = Min; for(int j = 1; j <= N; ++j) if(!vis[j] && low[j] > Map[pos][j]) low[j] = Map[pos][j]; } printf("%d\n",MAX); } int main() { int N,T; scanf("%d",&T); while(T--) { scanf("%d",&N); for(int i = 1; i <= N; ++i) for(int j = 1; j <= N; ++j) scanf("%d",&Map[i][j]); Prim(N); } return 0; }
POJ2485 Highways【Prim】