第九届河南理工大学算法程序设计大赛 正式赛L:最优规划(最小生成树)

本文介绍了一个最短路径问题的解决方案,通过最小生成树算法来确定连接所有城市的最短路径总长度。具体步骤包括:首先将已有的路径权重设为0,然后使用MST算法找出最小生成树。

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

单测试点时限: 1.0 秒

内存限制: 512 MB

有很多城市之间已经建立了路径,但是有些城市之间没有路径联通。为了联通所有的城市,现在需要添加一些路径,为了节约,需要满足添加总路径是最短的。

输入

第一行 333 个整数 n,m,sn, m, sn,m,s, 分别表示城市的数量、已经存在的路的数量、可修的路的数量。
之后的 mmm 行,每行 333 个整数 x,y,dx, y, dx,y,d,表示点 xxx 到点 yyy 有一条长度为 ddd 的已经存在的路径。
之后的 sss 行,每行 333 个整数 x,y,dx, y, dx,y,d,表示点 xxx 到点 yyy 有一条长度为 ddd 的可修的路径。
0&lt;n,m,s,d≤1050&lt;n,m,s,d≤10^50<n,m,s,d105

输出

输出一个整数表示需要添加的最短的路径长度。
若果无论如何也无法使得所有的城市联通,输出 Concubines can't do it.

样例

input

5 3 2
1 2 1
1 3 2
1 4 3
2 3 4
2 5 5

output

5

Solve

最小生成树裸题,前mmm条边的边权变成000,后sss条边的边权不变,进行MST

Code

#include<bits/stdc++.h>
#define ll long long
#define ms(a,b) memset(a,b,sizeof(a))
const int maxn=1e6+10;
const int maxm=1e3+10;
const int inf=(1<<30);
const ll INF=(1LL*1<<60);
using namespace std;
int f[maxn];
struct Edge
{
	int u,v,w;
}edge[maxn];
int tol;
void add(int u,int v,int w)
{
	edge[tol].u=u;
	edge[tol].v=v;
	edge[tol++].w=w;
}
bool cmp(Edge a,Edge b)
{
    return a.w<b.w;
}
int Find(int x)
{
    if(f[x]==x)
        return x;
    else
        return f[x]=Find(f[x]);
}
ll kru(int n)
{
    for(int i=0;i<=n;i++)
        f[i]=i;
    sort(edge,edge+tol,cmp);
    int cnt=0;
    ll ans=0;
    for(int i=0;i<tol;i++)
    {
        int u=edge[i].u;
        int v=edge[i].v;
        int w=edge[i].w;
        int tOne=Find(u);
        int tTwo=Find(v);
        if(tOne!=tTwo)
        {
            ans+=1LL*w;
            f[tOne]=tTwo;
            cnt++;
        }
    }
    if(cnt<n-1)
        return -1;
    else
        return ans;
}
int main()
{
	ios::sync_with_stdio(false);cin.tie(0);
    int n,m,s;
    cin>>n>>m>>s;
    int res=0;
    for(int i=0;i<m;i++)
    {
        int x,y,d;
        cin>>x>>y>>d;
        res=max(max(x,y),res);
        add(x,y,0);
        add(y,x,0);
    }
    int a1=kru(m);
    for(int i=0;i<s;i++)
    {
        int x,y,d;
        cin>>x>>y>>d;
        add(x,y,d);
        add(y,x,d);
    }
    if(kru(n)==-1)
        cout<<"Concubines can't do it."<<endl;
    else
        cout<<1LL*kru(n)<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值