繁忙的都市 最小生成樹 入門題
阿新 • • 發佈:2018-11-10
Code:
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=305;
const int maxn=100000+44;
int from[maxn],to[maxn],C[maxn],A[maxn];
int p[N];
int find(int x)
{
return p[x]==x?x:p[x]=find(p[x]);
}
int cmp(int i,int j)
{
return C[i]<C[j];
}
int main()
{
int n,m,ans;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)p[i]=i;
for(int i=1;i<=m;++i)
{
A[i]=i;
scanf("%d%d%d",&from[i],&to[i],&C[i]);
}
sort(A+1,A+1+m,cmp);
for(int i=1;i<=m;++i)
{
int cur=A[i];
int x=find(from[cur]);
int y=find(to[cur]);
if(x==y)continue;
p[x] =y,ans=C[cur];
}
printf("%d %d",n-1,ans);
return 0;
}