poj 2485 prim入门题目

来源:互联网 发布:mac怎么保存文档 编辑:程序博客网 时间:2024/05/29 07:29

Highways
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 30601 Accepted: 13910

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.

复习一下prim算法

#include <stdio.h>#include <string.h>#include <algorithm>#include <math.h>using namespace std;const int INF = 0x3f3f3f3f;const int maxd = 502;int map[maxd][maxd];bool vis[maxd];int low[maxd];int N;void prim(){int max = 0;memset(vis,false,sizeof(vis));memset(low,0,sizeof(low));vis[0] = true;for(int i = 1; i < N; i++){low[i] = map[0][i];}for(int i = 1; i < N; i++){int min = INF, temp,k;for(int j = 1; j < N; j++){if(!vis[j] && min > low[j]){min = low[j];k = j;}}vis[k] = true;if(max < min){max = min;}for(int j = 1; j < N; j++){if(low[j] >map[k][j] && !vis[j]){low[j] = map[k][j];}}}printf("%d\n",max);}int main(){int T;scanf("%d",&T);while(T--){scanf("%d",&N);int x;for(int i = 0; i < N; i++){for(int j = 0; j < N; j++){scanf("%d",&x);map[i][j] = x;}}prim();}return 0;}


0 0