最小生成树的板子;
使得连通块的数量减小到k即可!
数据有点水(printf("No Answer");根本没用到QAQ)。
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 7;
const int M = 1e4 + 7;
int f[N];
struct Node{ int s, t, w; }a[M];
bool cmp(Node x, Node y){ return x.w < y.w; }
int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); }
int main(){
int n, m, k, ans = 0;
scanf("%d%d%d", &n, &m, &k);
for(int i = 1;i <= n;i ++) f[i] = i;
for(int i = 1;i <= m;i ++)
scanf("%d%d%d", &a[i].s, &a[i].t, &a[i].w);
sort(a + 1, a + m + 1, cmp);
for(int i = 1;i <= m;i ++){
int fx = find(a[i].s), fy = find(a[i].t);
if(fx != fy){
f[fx] = fy;
ans += a[i].w;
n --;
}
if(n == k){
printf("%d", ans);
return 0;
}
}
printf("No Answer");
return 0;
}