HDU-6181 Two Paths(2017 Multi-University Training Contest - Team 10)

本文介绍了一种解决图中寻找次短路径问题的算法。在给定的无重边和自环的图中,两个玩家分别寻找从起点到终点的不同最短路径。文章通过实例详细解释了如何使用Dijkstra算法的变种来找到次短路径。

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

题目链接

HDU-6181

题目大意

nm Alice和Bob在图上走,Alice先走,并且走的是最短的路径。现在该Bob走,要走出一条最短的且不与Alice所走路线相同的路径。

数据范围

1T152n,m100000
1w1000000000(w)

解题思路

既要最短又要不同,裸裸的次短路。比赛的时候改了LL就把板子往上扔,一扔就过了,意外收获!


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
const int MaxN = 1e5;
typedef long long LL;
const LL INF = 1LL << 60;

int T;
int n, m, all;
int pre[2 * MaxN + 5], last[MaxN + 5], other[2 * MaxN + 5];
LL cost[2 * MaxN + 5];
LL dis[MaxN + 5]; //最短路
LL dist[MaxN + 5]; //次短路
struct Node
{
    int id;
    LL d;
    bool friend operator < (Node x, Node y)
    {
        return x.d > y.d;
    }
};

void build(int x, int y, LL w)
{
    pre[++all] = last[x];
    last[x] = all;
    other[all] = y;
    cost[all] = w;
}

void Dijkstra()
{
    priority_queue <Node> pq;
    for(int i = 1; i <= n; i++) {
        dis[i] = INF;
        dist[i] = INF;
    }
    dis[1] = 0; 

    Node tmp;
    tmp.d = 0, tmp.id = 1;
    pq.push(tmp);

    while(!pq.empty())
    {
        if(pq.empty()) break;
        Node now = pq.top();
        pq.pop();
        int ed = last[now.id], dr;
        if(dist[now.id] < now.d) continue;
        while(ed != -1) {
            dr = other[ed];
            //把dis[now.id]改为now.d就过了!
            //why!?
            LL D = now.d + cost[ed];

            if(D < dis[dr]) {
                dist[dr] = dis[dr];
                dis[dr] = D;
                tmp.d = dis[dr]; tmp.id = dr;
                pq.push(tmp);
            }
            else if(D > dis[dr] && D < dist[dr]) {
                dist[dr] = D;
                tmp.d = dist[dr]; tmp.id = dr;
                pq.push(tmp);
            }
            ed = pre[ed];
        }
    }
}

int main()
{
    scanf("%d", &T);
    while(T--) {
        scanf("%d %d", &n, &m);
        all = -1;
        memset(last, -1, sizeof(last));
        for(int i = 1; i <= m; i++) {
            int u, v;
            LL w;
            scanf("%d %d %lld", &u, &v, &w);
            build(u, v, w); build(v, u, w);
        }
        Dijkstra();
        printf("%lld\n", dist[n]);
    }
    return 0;
}

次短路有疑惑?点这里,希望能有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值