【最小生成树 kruskal】 hdu 1102 Constructing Roads

来源:互联网 发布:php 开发教育网站框架 编辑:程序博客网 时间:2024/05/21 17:04

题目链接:XXXXXXXXX


#include <iostream>#include <math.h>#include <algorithm>#include <string.h>#include <stdio.h>#define Maxn 10000using namespace std;int father[111], m;struct node{    int u, v, w;} edge[200000];bool cmp(node x, node y){    return x.w < y.w;}int find(int r){    if(r != father[r])        father[r] = find(father[r]);    return father[r];}void kru(){    int ans = 0;    for(int i = 0; i < m; i++)    {        int a = edge[i].u;        int b = edge[i].v;        a = find(a), b = find(b);        if(a != b)        {            father[a] = b;            ans += edge[i].w;        }    }    printf("%d\n", ans);}int main(){    int n;    while( scanf("%d", &n) != EOF)    {        m = 0;        for(int i = 0; i <= n; i ++)            father[i] = i;        for(int i = 1; i <= n; i ++)        {            for(int j = 1; j <= n; j ++)            {                int k;                scanf("%d", &k);                if(j < i)                {                    edge[m].u = i;                    edge[m].v = j;                    edge[m].w = k;                    m++;                }            }        }        sort(edge, edge+m, cmp);        int q;        scanf("%d", &q);        while(q--)        {            int a, b;            scanf("%d%d", &a, &b);            a = find(a), b = find(b);            father[a] = b;        }        kru();    }    return 0;}


0 0