poj2485

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

解析:最小生成树问题,涉及算法---Prim算法

题意:在各个村庄中修建高速公路,使各个村庄都相连,要求建造公路最短,输出建造的公路中最长的一段

代码:

#include"stdio.h"
#include "string.h"
#define max 501
#define INF 999999
int road[max][max];
int n;
int main(){
	int i,j,k1,t,min,closedge[max],flag[max];
	int cases;
	scanf("%d",&cases);
	while(cases--){
		scanf("%d",&n);
    	for(i=0;i<n;i++)    //创建村庄距离的二维数组
	       for(j=0;j<n;j++)
	       	 scanf("%d",&road[i][j]);
	    for(j=0;j<n;j++) {        //将与结点0相连的村庄的距离赋值给closedge数组
		    closedge[j]=road[0][j];}
            memset(flag,0,sizeof(flag));   //将flag数组全部赋值为0
		flag[0]=1;           //已经用过的村庄结点的flag标志域赋值变为1
	    for(i=1;i<n;i++){
	    	min=INF;
	    	k1=-1;
	        for(j=0;j<n;j++)    //找与结点0距离最短的村庄j
	        	if(!flag[j]&&min>closedge[j]){
	        		min=closedge[j];
	        		k1=j;   
	        	}
	    	flag[k1]=1; //将j并入已用结点中//highlen=highlen>min?highlen:min;
	        for(j=0;j<n;j++){   //在与j相连的结点中查找是否有更短的边与另一个结点相连
	        	if(!flag[j]&&road[k1][j]<closedge[j])
	        	   closedge[j]=road[k1][j];   //根据prim算法构建最小生成树图理解
	        }
	    } 
	    t=0;     

	    for(i=0;i<n;i++)
		if(t<closedge[i])
		    t=closedge[i];     //highlen=highlen>min?highlen:min;找所建公路最大长度并输出

	     printf("%d\n",t);
         
	}
	return 0;
}

新学用法:memset(flag,0,sizeof(flag));   memset()函数在"string.h"头文件中  可以缩短运算时间


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值