nyoj38

布线问题

Kruskal最短路模板题:
思路:
直接Kruskal

//
// Created by luozujian on 17-10-14.
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#define INF 0x3f3f3f3f
using namespace std;
const int maxv = 5e2+5;
const int maxe = maxv*(maxv-1)/2;
struct node{
    int from , to ,cost;
};
node es[maxe];
int a[maxv];
int par[maxv];
int E,V;
bool cmp(node a,node b)
{
    return a.cost < b.cost;
}
void Init_union_find(int V)
{
    for(int i=1;i<=V;i++) par[i] = i;
}
int find(int x)
{
    if(par[x] == x)
    {
        return x;
    }
    else return par[x] = find(par[x]);
}
bool same(int a,int b)
{
    int fx = find(a),fy = find(b);
    if(fx == fy)
    {
        return true;
    }
    else
    {
        return false;
    }
}
void unit(int a,int b)
{
    int fx = find(a),fy = find(b);
    par[fx] = fy;
}
void Kruskal()
{
    sort(es,es+E,cmp);
    Init_union_find(V);
    int res = 0;
    for(int i=0;i<E;i++)
    {
        if(!same(es[i].to,es[i].from))
        {
            res+=es[i].cost;
            unit(es[i].to,es[i].from);
        }
    }
    int ans = INF;
    for(int i=1;i<=V;i++)
    {
        ans=min(ans,a[i]);
    }
    printf("%d\n",ans+res);
}
void solve()
{
    Kruskal();
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&V,&E);
        for(int i=0;i<E;i++)
        {
            int s,t,cost;
            scanf("%d%d%d",&s,&t,&cost);
            es[i].from = s;
            es[i].to = t;
            es[i].cost = cost;
        }
        for(int i=1;i<=V;i++)
        {
            scanf("%d",&a[i]);
        }
        solve();
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值