您的位置:首页 > 其它

最小生成树-prime算法

2016-05-01 20:02 363 查看
prime算法的基本思想

1.清空生成树,任取一个顶点加入生成树

2.在那些一个端点在生成树里,另一个端点不在生成树里的边中,选取一条权最小的边,将它和另一个端点加进生成树
3.重复步骤2,直到所有的顶点都进入了生成树为止,此时的生成树就是最小生成树

1090. Highways

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

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


1

3
0 990 692
990 0 179
692 179 0

Sample Output


692

#include<iostream>

using namespace std;

const int MAX=500;
const int INF=65536;
int arc[MAX][MAX];
bool visited[MAX];
int cost[MAX];
int longest;

void prime(int curr,int city){
visited[curr]=true;
int min=INF,index;
longest=0;
for(int i=0;i<city;i++){
cost[i]=arc[curr][i];
}
for(int i=1;i<city;i++){
min=INF;
for(int j=0;j<city;j++){
if(!visited[j]&&cost[j]<min){
min=cost[j];
index=j;
}
}
visited[index]=true;
if(min>longest)
longest=min;
for(int j=0;j<city;j++){
if(!visited[j]&&arc[index][j]<cost[j]){
cost[j]=arc[index][j];
}
}
}

}

int main(){

int t,city;
cin>>t;
while(t--){
for(int i=0;i<MAX;i++)
visited[i]=false;
cin>>city;
for(int i=0;i<city;i++){
for(int j=0;j<city;j++){
cin>>arc[i][j];
}
}
prime(0,city);
cout<<longest<<endl;
if(t)
cout<<endl;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: