HDU-1102 Constructing Roads

本文介绍了一种使用Kruskal算法解决最小生成树问题的方法。通过输入城镇间距离矩阵及已知连通信息,实现自动寻找最短路径,避免重复建设道路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int n, q, a , b, temp, pos, cnt, ans;
struct node
{
    int op;
    int ed;
    int len;
    bool operator < (const node Next) const
    {
        return len < Next.len;
    }
} edge[10005];
int root[105];

int Find(int x)
{
    return root[x] == x ? x : root[x] = Find(root[x]);
}

void Kruskal()
{
    ans = 0;
    for(int i = 0; i < pos; i ++)
    {
        int x = Find(edge[i].op);
        int y = Find(edge[i].ed);
        if(x != y)
        {
            root[y] = x;
            ans += edge[i].len;
            cnt ++;
        }
        if(cnt == n - 1)
            break;
    }
}

int main()
{
    while(~scanf("%d", & n))
    {
        pos = 0;
        for(int i = 1; i <= n; i ++)
        {
            for(int j = 1; j <= n; j ++)
            {
                scanf("%d", & temp);
                if(!temp)
                    continue;
                edge[pos].len = temp;
                edge[pos].op = i;
                edge[pos].ed = j;
                pos ++;
            }
        }
        for(int i = 1; i <= n; i ++)
            root[i] = i;
        sort(edge, edge + pos);
        scanf("%d", & q);
        cnt = 0;
        while(q --)
        {
            scanf("%d %d", & a, & b);
            int x = Find(a);
            int y = Find(b);
            if(x != y)
            {
                root[y] = x;
                cnt ++;
            }
        }
        Kruskal();
        printf("%d\n", ans);
    }
    return 0;
}

题意:
输入n。之后n行分别输入n个数。第i行第j列代表i城镇到j城镇的距离。之后输入q。之后q行分别输入a b。表示a城镇与b城镇已连通,不需要建设道路。
题解:
Kruskal继续。把a b先处理连接就好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值