Prim算法之二
//sicily 1090. Highways
#include<iostream> //最小生成树 Prim算法
using namespace std;
struct MST //最小生成树的边
{
int st,ed,w;
}mst[1000];
int n,len,edge[1000][1000];
void Prim()
{
int i,j,k;
for(i=0;i<n-1;i++) //默认选择第1个节点加入生成树
{
mst[i].st=0;mst[i].ed=i+1;
mst[i].w=edge[0][i+1];
}
for(i=0;i<n-1;++i) //求n-1条边
{
int min=100000;
for(j=i;j<n-1;++j)
{
if(mst[j].w<min) //求最小权值边
{
min=mst[j].w;k=j;
}
}
swap(mst[k],mst[i]); //最小边移至前端
int p=mst[i].ed;
len=max(len,mst[i].w);
for(j=i+1;j<n-1;++j) //更新后面的边
{
int com=edge[p][mst[j].ed];
if(com<mst[j].w)
{
mst[j].w=com;mst[j].st=p;
}
}
}
}
int main()
{
int cases;
cin>>cases;
for(int id=1;id<=cases;++id)
{
cin>>n;
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
cin>>edge[i][j];
len=0; //len保存最小生成树的最长边
Prim();
if(id>1)
cout<<endl;
cout<<len<<endl;
}
return 0;
}