2023天梯分组赛 L2-4(最短路)

该代码实现了一个Dijkstra算法求解图中节点间最短路径的问题。程序首先读取节点数、边数和起始节点,然后构建邻接表并初始化最短路径数组。通过优先队列进行迭代更新,找到从起始节点到所有其他节点的最短时间。最后输出每个节点的最短路径时间。
摘要由CSDN通过智能技术生成

代码及其注释: 

#include <bits/stdc++.h>

using namespace std;

#define endl "\n"
#define debug cout<<"debug"<<endl
mt19937 rd(time(0));
typedef long long ll;
typedef long double ld;
typedef pair<int, int> PII;
const double eps = 1e-8;
const double PI = 3.14159265358979323;
const int N = 2e5+10, M = 2*N, mod = 1e9+7;
const int INF = 0x3f3f3f3f;

int n, m, k;

int h[N], e[M], ne[M], idx;
int a[N], g[N], st[N];

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void dijkstra()
{
    memset(g, 0x3f, sizeof g); // 时间为边权, g[i]为i点解封的最短时间
    priority_queue<PII, vector<PII>, greater<PII> > p;
    g[k] = a[k];
    p.push({a[k], k}); // 时间为边权入队

    while(p.size())
    {
        auto t = p.top(); p.pop();
        int ver = t.second;
        if(st[ver]) continue;
        st[ver] = 1;

        for(int i = h[ver]; ~i; i = ne[i])
        {
            int j = e[i];
            if(g[j] >= g[ver]) // 用时间更新, 找每个点的最小时间即可, g[j] >= g[ver] 表示有更早的点ver能够到达j
            {
                g[j] = g[ver];
                if(g[j] < a[j]) g[j] = a[j]; //  g[j] < a[j] 即但最短时间比解封时间还短则错误
                p.push({g[j], j}); // 更新完入队更新其他点
            }
        }
    }
}

void solve()
{
    cin>>n>>m>>k;
    memset(h, -1, sizeof h);

    for(int i = 1; i<=n; i++)
    {
        int x; cin>>x;
        a[x] = i;
    }
    for(int i = 1; i<=m; i++)
    {
        int x, y; cin>>x>>y;
        add(x, y), add(y, x);
    }
    dijkstra();

    for(int i = 1; i<=n; i++) cout<<g[i]<<" \n"[i == n];
}

int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    int T;
    T = 1;
//    cin>>T;
    while(T -- )
    {
        solve();
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值