洛谷P1396 营救

这篇博客讲解了如何使用Kruskal算法解决营救问题,特别强调了如何在并查集中找到起点到终点的最长路径,即拥挤度最大的边。作者提供了C++代码示例,适合理解Kruskal排序在实际问题中的应用。

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

题目链接:营救 - 洛谷

非常模板的kruskal, 唯一需要想的地方是起点到终点这段"最大的拥挤度"如何计算

因为kruskal是排序后进行的, 所以当起点和重点都在并查集中时, 最后进入并查集的那条边就是拥挤度最大的的边

ac代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstring>
#include <string>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define ll long long
#define endl "\n"
#define rep(i, a, b) for (ll i = (a); i <= (b); i++)
#define repr(i, a, b) for (ll i = (a); i < (b); i++)
#define rrep(i, a, b) for (ll i = (b); i >= (a); i--)
#define rrepr(i, a, b) for (ll i = (b); i > (a); i--)
#define min(a,b) (a)<(b)?(a):(b)
#define max(a,b) (a)>(b)?(a):(b)
#define yes puts("YES");
#define no puts("NO");
#define debug puts("here!");

ll cnt,n,m,t,ans,ant,s;
const int N=1e5+10;
ll arr[N];
string str;

inline ll read()
{
    char c = getchar();int x = 0,s = 1;
    while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}//是符号
    while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}//是数字
    return x*s;
}

struct Edge
{
    ll u,v,w;
}edges[N];

bool cmp(Edge a,Edge b)
{
    return a.w<b.w;
}

ll find(ll x)
{
    if(x!=arr[x]) arr[x]=find(arr[x]);
    return arr[x];
}

void kruskal()
{
    sort(edges+1,edges+1+m,cmp);
    rep(i,1,m)
    {
        ll u,v,w;
        u=edges[i].u;
        v=edges[i].v;
        w=edges[i].w;
        u=find(u);
        v=find(v);
        if(u!=v)
            arr[u]=v;
        if(find(s)==find(t))
        {
            cout<<edges[i].w<<endl;
            return;
        }
    }
}

void solve()
{
    cin>>n>>m>>s>>t;
    ll u,v,w;
    rep(i,1,m)
    {
        cin>>u>>v>>w;
        edges[i]={u,v,w};
    }
    rep(i,0,n) arr[i]=i;
    kruskal();
    return;
}

int main()
{
    ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
    solve();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值