您的位置:首页 > 其它

[kuangbin带你飞]专题六 最小生成树 D

2017-01-17 15:30 471 查看

题意:

给每两个点之间的距离,然后给几个点已经相连,问最小生成树。。

tip:

显然用kru之间把已知放在一个集里面很简单。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
const int maxm = 10010;
const int maxn = 110;
using namespace std;
int tot,root[maxn],n,m;
struct node{
int u,v,w;
bool operator < (const node &b)const{
return w < b.w;
}
}edges[maxm];

void add(int u,int v,int w){
edges[tot].u=u;edges[tot].v= v;edges[tot++].w=w;
}
int findroot(int x){
return x==root[x]?x:root[x]=findroot(root[x]);
}
void kru(){
int ans = 0;
for(int i = 0 ; i < tot ;i++){
int x = findroot(edges[i].v),y = findroot(edges[i].u);
if(x == y)  continue;
else{
ans+=edges[i].w;
root[x] = root[y];
}
}
printf("%d\n",ans);
}

void init(){
tot = 0;
for(int i = 1; i <= n ; i++)    root[i] = i;
for(int i = 1 ; i <= n ; i++)
for(int j = 1; j <= n ; j++){
int k;
scanf("%d",&k);
if(i < j)   add(i,j,k);
}
sort(edges,edges+tot);
scanf("%d",&m);
for(int i = 0 ; i < m ;i++){
int a,b;
scanf("%d%d",&a,&b);
int x = findroot(a),y = findroot(b);
if(x == y)  continue;
root[x] = root[y];
}
}

int main(){
while(~scanf("%d",&n)){
init();
kru();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: