No1090. Highways

来源:互联网 发布:百度域名 编辑:程序博客网 时间:2024/06/08 16:10

一、题目描述

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 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. 

Output

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.
This problem contains multiple test cases!
The first line of a multiple input is an integer T, then a blank line followed by T input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of T output blocks. There is a blank line between output blocks.

Sample Input

130 990 692990 0 179692 179 0

Sample Output

692

二、方法一

Prim算法:

普里姆算法Prim算法),可在加权连通图里搜索最小生成树。意即由此算法搜索到的边子集所构成的树中,不但包括了连通图里的所有顶点,且其所有边的权值之和亦为最小。详细描述请见:http://www.cnblogs.com/biyeymyhjob/archive/2012/07/30/2615542.html

以一个顶点为起点,计算该点能到达的所有点的边中最小的边,并选取该边的另一个端点,与该节点结合为一个点,然后更新所有边到起点的距离,如果有路过新加入的节点而到达起点更短的点,则更新该点到起点的距离。然后计算下一个最短边对应的顶点加入到与起点相融合的集合中,更新到达起点的边长,直到所有顶点都与起点融合在一起了。

代码实现:

#include<iostream>using namespace std;#define MAX 500#define INF 65536int graph[MAX][MAX];int temp[MAX];int min(int n){    int min=INF;    int result=0;    for(int i=0;i<n;i++){        if(temp[i]<min&&temp[i]>0){            min=temp[i];            result=i;        }    }    return result;}int prim(int n){    int max=0;    for(int i=0;i<n;i++)        temp[i]=graph[0][i];    for(int i=1;i<n;i++){        int k=min(n);        if(temp[k]>max) max=temp[k];        temp[k]=0;        for(int j=0;j<n;j++){            if(graph[k][j]<temp[j])                temp[j]=graph[k][j];        }    }    return max;}int main(){    int t;    cin>>t;    while(t--){        int n;        cin>>n;        for(int i=0;i<n;i++){            for(int j=0;j<n;j++){                cin>>graph[i][j];            }        }        cout<<prim(n)<<endl;        if(t) cout<<endl;    }    return 0;}

三、方法二