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

来源:互联网 发布:淘宝客刷销量有什么用 编辑:程序博客网 时间:2024/06/01 10:22

题意:

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

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();    }}
0 0
原创粉丝点击