poj 2485 Highways ( prim )

来源:互联网 发布:苹果系统mac系统下载 编辑:程序博客网 时间:2024/04/16 12:39

Highways
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 28419 Accepted: 12953

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

130 990 692990 0 179692 179 0

Sample Output

692
题意:求最小生成树中的最大边权。

题目给出了map图,就用prim算法吧。

代码:

#include<cstdio>#include<cstring>#include<algorithm>#define INF 0x3f3f3fusing namespace std;int dis[510];int map[510][510];int vis[510];int maxd;int prim(int n){memset(vis,0,sizeof(vis));memset(dis,INF,sizeof(dis));dis[1]=0;//vis[1]=1;//如果执行这步,下面就执行n-1步 //for(int i=2;i<=n;i++)//{//dis[i]=map[1][i];//}maxd=0;for(int i=1;i<=n;i++)//执行n次 {int k=-1;for(int j=1;j<=n;j++){if(!vis[j]&&(k==-1||dis[j]<dis[k]))k=j;}vis[k]=1;if(maxd<dis[k])maxd=dis[k];for(int j=1;j<=n;j++){if(!vis[j]&&dis[j]>map[k][j])dis[j]=map[k][j];}}return maxd;}int main(){int t,n;scanf("%d",&t);while(t--){scanf("%d",&n);memset(map,INF,sizeof(map));for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){scanf("%d",&map[i][j]);} }  printf("%d\n",prim(n)); }  return 0;}

0 0
原创粉丝点击