给定部分路径后的最小生成树
注意给的路径有可能构成回路
#include<stdio.h>
#include<stdlib.h>
#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
int parent[6001];
int k;
int f[6000][6000];
struct edge
{
int u,v,w;
} edges[6001];
int compare(const void *a, const void *b)
{
return (*(edge *)a).w - (*(edge *)b).w;
}
int findset(int x)
{
int tmp,s;
s=x;
while (parent[s]>=0) s=parent[s];
while (s!=x)
{
tmp=parent[x];
parent[x]=s;
x=tmp;
}
return s;
}
void unionset(int r1,int r2)
{
int rr1,rr2;
rr1=findset(r1);
rr2=findset(r2);
int tmp=parent[rr1]+parent[rr2];
if (rr1==rr2) return;
if (parent[rr1]>parent[rr2]) {
parent[rr1]=rr2;
parent[rr2]=tmp;
}
else {
parent[rr2]=rr1;
parent[rr1]=tmp;
}
}
int main()
{
int q,n,m,num,ans,x,y;
scanf("%d",&n);
m=0;
for (int i=0;i<=n;i++) parent[i]=-1;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
scanf("%d",&f[i][j]);
if (i>j){
edges[m].u=i;
edges[m].v=j;
edges[m].w=f[i][j];
m++;
}
}
scanf("%d",&q);
int t=0;
for (int i=1;i<=q;i++)
{
scanf("%d%d",&x,&y);
if (findset(x-1)!=findset(y-1)) {
unionset(x-1,y-1);
t++;
}
}
qsort(edges,m,sizeof(edges[0]),compare);
ans=0;num=0;
for (int i=0;i<m;i++)
{
if (findset(edges[i].u)!=findset(edges[i].v))
{
num++;
ans=ans+edges[i].w;
unionset(edges[i].u,edges[i].v);
}
if (num>=n-1-t) break;
}
printf("%d\n",ans);
}