Highways
Time Limit: 1000 MS Memory Limit: 65536 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
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 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.
Output
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
1 3 0 990 692 990 0 179 692 179 0
Sample Output
692
///走的路最长 花费时间最小 #include <iostream> #include <stdio.h> #include <string.h> using namespace std; #define INF 0x1f1f1f1f int cost[505][505],n; int prim(int cost[][505],int n) { ///前提的初始化 int low[65537]; int low_ss; int vis[505]; int i,j,point,p,s=1,m=1; int min,res=0; vis[s]=true; memset(vis,false,sizeof(vis)); memset(low,INF,sizeof(low)); ///进行遍历 while(true) { low_ss=INF; if(n==m) break; for(int i=2; i<=n; i++) { if(!vis[i]&&low[i]>cost[s][i]) ///没走过&&各节点到1号位的距离 low[i]=cost[s][i]; ///更新距离为输入的 if(!vis[i]&&low_ss>low[i]) ///没走过&&该路径能走 { low_ss=low[i]; ///标记该路径 point=i; } } if(res<low_ss) ///寻找最长路径 res=low_ss; s=point; vis[s]=true; m++; } return res; } int main() { int t,n; int a[505][505]; scanf("%d",&t); while(t--) { ///输入部分 scanf("%d",&n); for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { scanf("%d",&a[i][j]); } } ///输出部分 printf("%d\n",prim(a,n)); } } prim的模板题 加一个判断(判断是否走的路径最长)
poj2485最小生成树prim