HDU1102
题解:已经有了的边就合并,然后剩下的边求最小生成树即可。
代码:
#include <bits/stdc++.h>
using namespace std;
int const N = 200 + 10;
int const M = 10000 + 10;
int n,m,q,a[N][N],fa[N];
struct Edge
{
int u,v,dist;
Edge(){}
Edge(int uu,int vv,int dd):u(uu),v(vv),dist(dd){}
}p[M];
int find(int x){
return x == fa[x] ? x : (fa[x] = find(fa[x]));
}
bool cmp(Edge a,Edge b){
return a.dist < b.dist;
}
int Kruskal(){
int sum = 0,e = 0;
sort(p+1,p+1+m,cmp);
for(int i=1;i<=m;i++){
if(e == n-1) break;
int x = find(p[i].u), y = find(p[i].v);
if(x != y){
e++;
sum += p[i].dist;
fa[x] = y;
}
}
return sum;
}
int main(){
while(~scanf("%d",&n)){
m = 0;
for(int i=1;i<=n;i++) fa[i] = i;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
scanf("%d",&a[i][j]);
p[++m] = Edge(i,j,a[i][j]);
}
scanf("%d",&q);
for(int i=0;i<q;i++){
int x,y; scanf("%d%d",&x,&y);
int fx = find(x), fy = find(y);
fa[fx] = fy;
}
int ans = Kruskal();
printf("%d\n",ans);
}
}