洛谷P1821 [USACO07FEB]Silver Cow Party S 题解 最短路变形题

题目链接:https://www.luogu.com.cn/problem/P1821

题目大意:求所点 \(i\) 的从起点出发到 \(i\) 然后再从 \(i\) 返回起点的最短路径的最大值。

解题思路:
求起点到所有点的最短路可以直接得到。

求所有点到起点的最短路,可以建反图,然后用最短路算法求。

所以这道题相当于求两边最短路,其中第二遍是建反图求最短路。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010, maxm = 200010;
struct Edge {
    int v, w, nxt;
    Edge() {};
    Edge(int _v, int _w, int _nxt) { v = _v; w = _w; nxt = _nxt; }
} edge[maxm];
int n, m, head[maxn], ecnt;
void init() {
    ecnt = 0;
    memset(head, -1, sizeof(int)*(n+1));
}
void addedge(int u, int v, int w) {
    edge[ecnt] = Edge(v, w, head[u]); head[u] = ecnt ++;
}
struct Node {
    int u, dis;
    Node() {};
    Node(int _u, int _dis) { u = _u; dis = _dis; }
    bool operator < (const Node& x) const {
        return dis > x.dis;
    }
};
priority_queue<Node> que;
int dis[maxn];
bool vis[maxn];
void dijkstra(int s) {
    for (int i = 1; i <= n; i ++) {
        dis[i] = -1;
        vis[i] = false;
    }
    while (!que.empty()) que.pop();
    dis[s] = 0;
    que.push(Node(s, 0));
    while (!que.empty()) {
        Node nd = que.top();
        que.pop();
        int u = nd.u;
        if (vis[u]) continue;
        vis[u] = true;
        for (int i = head[u]; i != -1; i = edge[i].nxt) {
            int v = edge[i].v, w = edge[i].w;
            if (!vis[v] && (dis[v] == -1 || dis[v] > dis[u] + w)) {
                dis[v] = dis[u] + w;
                que.push(Node(v, dis[v]));
            }
        }
    }
}
int s, u[maxm], v[maxm], w[maxm];
int dis1[maxn], dis2[maxn];
int main() {
    cin >> n >> m >> s;
    for (int i = 0; i < m; i ++) cin >> u[i] >> v[i] >> w[i];
    init();
    for (int i = 0; i < m; i ++) addedge(u[i], v[i], w[i]);
    dijkstra(s);
    for (int i = 1; i <= n; i ++) dis1[i] = dis[i];
    init();
    for (int i = 0; i < m; i ++) addedge(v[i], u[i], w[i]);
    dijkstra(s);
    for (int i = 1; i <= n; i ++) dis2[i] = dis[i];
    int ans = 0;
    for (int i = 1; i <= n; i ++) if (dis1[i] != -1 && dis2[i] != -1) ans = max(ans, dis1[i] + dis2[i]);
    cout << ans << endl;
    return 0;
}
posted @ 2020-05-22 02:46  quanjun  阅读(133)  评论(0编辑  收藏  举报