poj2485 highwaysC语言编写

时间:2023-03-08 16:30:37
/*Highways
Time Limit: 1000MS

Memory Limit: 65536K
Total Submissions: 33595

Accepted: 15194
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<stdio.h>
#define v 501 //顶点的最大数目 
#define max 66666 //用于比较的数字,比max 大视为不相邻 
int map[v][v];//存储顶点的关系 
void prim(int n) 
{int i,j;
 int min;//距离生成树最近的距离 
int way[v];//存放各顶点到树的距离 
 int r=0;//每次放入树中顶点的标号 
 int p[v];//判断顶点是否在树里,并存放顶点标号
 int ans=0;//存放最小生成树里的最大权值(两顶点之间最大距离) 
  for(i=0;i<n;i++) p[i]=-1;//不在树里记为-1‘在记为1
 p[0]=0;//开始前把0顶点放在树里 
for(i=0;i<n;i++)
  way[i]=map[i][r];//其余顶点到--树--的距离 
for(i=1;i<n;i++)//判断n-1次 way[n]
{min=max;
 for(j=0;j<n;j++)//在可以比较的距离里面选择最近的标号出来 
            if(way[j] && way[j]<min)
               { min=way[j];  r=j; }  
     p[r]=r;//选中的顶点放到数组里 
 way[r]=0;//该顶点在树里故距离变成0 
     if(ans<min) ans=min;//更新ans的值 
     for(j=0;j<n;j++)//更新way 
      {
  if(way[j] && map[j][r]<way[j])
                 way[j]=map[j][r]; 
 }

printf("%d\n",ans);
 } 
int main()  
{  
    int i,j,t,n;  
    //t是多少组数据。n是多少个城市 
    scanf("%d", &t);//输入T组数据 
    while(t--)  
    {  
        scanf("%d",&n);//n 个城市 
        for(i=0;i<n;i++) //输入城市间的距离 
           for(j=0;j<n;j++)  
                scanf("%d",&map[i][j]);  
    prim(n)   ;       
    } 
    return 0;  
}