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.
#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; }
此题关键要理解输出的定义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 minimu...