题目:
思路:
只要算出需要连接几条边应该就没问题了
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#define maxn 1111
using namespace std;
int n,m,k,u,v,w;
int fa[maxn];
struct edge
{
int x,y,z;
bool operator<(const edge &e1)const
{
return z<e1.z;
}
}e[maxn*maxn];
int getfa(int x)
{
return (x==fa[x])?x:(fa[x]=getfa(fa[x]));
}
void merge(int x,int y)
{
int xx=getfa(x),yy=getfa(y);
if (xx==yy) return;
fa[xx]=yy;
}
int main()
{
cin>>n>>m>>k;
int ans=0,cnt=0;
for (int i=1;i<=n;i++) fa[i]=i;
for (int i=1;i<=m;i++)
{
cin>>u>>v>>w;
e[i]={u,v,w};
}
sort(e+1,e+m+1);
//for(int i=1;i<=m;i++) cout<<e[i].x<<" "<<e[i].y<<" "<<e[i].z<<endl;
if(k>n) cout<<"No Answer"<<endl;
else
{
for(int i=1;i<=m;i++)
{
//cout<<"cnt="<<cnt<<" "<<"ans="<<ans<<endl;
if(cnt==n-k) break;
if(getfa(e[i].x)!=getfa(e[i].y))
{
merge(e[i].x,e[i].y);
ans+=e[i].z;
cnt++;
}
}
cout<<ans<<endl;
}
return 0;
}