POJ2485 求最小生成树的最大边长度

此题关键要理解输出的定义

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算法稍作变化即可AC

Source Code

Problem: 2485   User: yangliuACMer
Memory: 1232K   Time: 750MS
Language: C++   Result: Accepted
#include <iostream>
#define MAXN 500
#define inf 65537
typedef int elem_t;
using namespace std;


elem_t prim(int n,elem_t mat[MAXN][MAXN],int* pre){
	elem_t min[MAXN],ret=0,maxLen=-1;
	int v[MAXN],i,j,k;
	for (i=0;i<n;i++)
		min[i]=inf,v[i]=0,pre[i]=-1;
	for (min[j=0]=0;j<n;j++){
		for (k=-1,i=0;i<n;i++)
			if (!v[i]&&(k==-1||min[i]<min[k]))
				k=i;
			ret+=min[k];
			if(maxLen < min[k]){
				maxLen = min[k];
			}
			for (v[k]=1,i=0;i<n;i++)
				if (!v[i]&&mat[k][i]<min[i])
					min[i]=mat[pre[i]=k][i];
	}
	return maxLen;
}

int main(){
	int n,i,j,result,m;
	int pre[MAXN];
	int distance[MAXN][MAXN];
	int maxLen = -1;
	cin>>m;
	while(m--){
		cin>>n;
		for (i = 0;i < n;i++)
			for (j = 0;j < n;j++)
				{
					cin>>distance[i][j];
				}
		result  = prim(n,distance,pre);
		cout<<result<<endl;
	}
		return 0;
}


你可能感兴趣的:(算法,Integer,ini,each,output,distance)