POJ - 3255 -- Roadblocks

本文通过一个具体的POJ题目介绍了次短路问题及其求解方法,并使用Dijkstra算法进行实现。代码中详细展示了如何构建图结构、更新节点距离及次短距离等关键步骤。

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

题目来源:http://poj.org/problem?id=3255

次短路模板题。Dijkstra算法实现。

代码:

#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define ll long long
using namespace std;
const int maxm = 1e5 + 10;
const int maxn = 5e3 + 10;
int head[maxn], cnt, n, m, dis[maxn], dis1[maxn];
typedef pair<int, int> P;
priority_queue<P, vector<P>, greater<P> > q;
struct edge {
    int to, next, vi;
} e[maxm * 2];
void ins(int x, int y, int z) {
    e[++cnt].to = y;
    e[cnt].next = head[x];
    e[cnt].vi = z;
    head[x] = cnt;
}
int main() {
    while (~scanf("%d%d", &n, &m)) {
        cnt = 0;
        memset(head, 0, sizeof(head));
        memset(dis, 63, sizeof(dis));
        memset(dis1, 63, sizeof(dis1));
        int x, y, z;
        for (int i = 1; i <= m; ++i) {
            scanf("%d%d%d", &x, &y, &z);
            ins(x, y, z);
            ins(y, x, z);
        }
        dis[1] = 0;
        q.push(P(0, 1));
        while (!q.empty()) {
            P u = q.top();
            q.pop();
            int v = u.second;
            for (int i = head[v]; i; i = e[i].next) {
                if (dis[e[i].to] > u.first + e[i].vi) {
                    dis1[e[i].to] = dis[e[i].to];
                    dis[e[i].to] = u.first + e[i].vi;
                    q.push(P(dis[e[i].to], e[i].to));
                } else if (dis1[e[i].to] > u.first + e[i].vi && dis[e[i].to] < u.first + e[i].vi) {
                    dis1[e[i].to] = u.first + e[i].vi;
                    q.push(P(dis1[e[i].to], e[i].to));
                }
            }
        }
        printf("%d\n", dis1[n]);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值