POJ - 3255 -- Roadblocks

版权声明: https://blog.csdn.net/moon_sky1999/article/details/81809394

题目来源: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;
}

猜你喜欢

转载自blog.csdn.net/moon_sky1999/article/details/81809394