https://vijos.org/p/1234
求一个不完全最小生成树,代码如下,一个简单的Kuskal
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
#include<cmath>
#define ms(i,j) memset(i, j, sizeof(i));
using namespace std;
//边
struct ed
{
int x;
int y;
int l;
}edge[10005];
int n,m,k;
//并查集
int father[1005];
int find(int x)
{
if (father[x]!=x) father[x] = find(father[x]);
return father[x];
}
int merge(int r1, int r2)
{
int x = find(r1);
int y = find(r2);
if (x!=y) father[x] = y;
}
//快速排序
void qs(int l, int r)
{
int i=l, j=r, x=edge[(l+r)/2].l;
do
{
while (edge[i].l<x) i++;
while (edge[j].l>x) j--;
if (i<=j)
{
ed t = edge[i];
edge[i] = edge[j];
edge[j] = t;
i++,j--;
}
} while (i<=j);
if (i<r) qs(i,r);
if (l<j) qs(l,j);
}
//Kruskal
int Kruskal()
{
int cnt = n;
int tot = 0;
for (int i=1;i<=m;i++)
{
if (find(edge[i].x)!=find(edge[i].y))
{
merge(edge[i].x, edge[i].y);
tot+=edge[i].l;
cnt--;
if (cnt<=k) break;
}
}
return tot;
}
int main ()
{
scanf("%d%d%d", &n, &m, &k);
for (int i=1;i<=n;i++) father[i] = i;
if (n<k) {printf("No Answer\n"); return 0;}
for (int i=1;i<=m;i++)
{
scanf("%d%d%d", &edge[i].x,&edge[i].y,&edge[i].l);
}
qs(1,m);
printf("%d\n", Kruskal());
return 0;
}