很简单,照搬kruskal算法的模板稍微改动一下就可以了
#include<bits/stdc++.h>
using namespace std;
const int N=1005;
const int M=10005;
int n,m,k;
int minsum=0;
int parent[N];
struct Edge
{
int x,y,l;
}edge[M];
void initial()
{
for(int i=1;i<=n;i++)
{
parent[i]=-1;
}
}
bool cmp(Edge a,Edge b)
{
return a.l<b.l;
}
int find_root(int x)
{
while(parent[x]!=-1)
{
x=parent[x];
}
return x;
}
void kruskal()
{
sort(edge+1,edge+1+m,cmp);
for(int i=1;i<=m;i++)
{
int x_root=find_root(edge[i].x);
int y_root=find_root(edge[i].y);
if(x_root!=y_root)
{
parent[x_root]=y_root;
minsum+=edge[i].l;
n--;
if(n==k) break;
}
}
}
int main()
{
cin>>n>>m>>k;
initial();
for(int i=1;i<=m;i++)
{
cin>>edge[i].x>>edge[i].y>>edge[i].l;
}
kruskal();
if(n==k)
cout<<minsum;
else
cout<<"No Answer";
}