当前位置: 代码迷 >> 综合 >> Silver Cow Party POJ - 3268(dijkstra + 连接表 + 优先队列)
  详细解决方案

Silver Cow Party POJ - 3268(dijkstra + 连接表 + 优先队列)

热度:87   发布时间:2023-12-07 00:26:42.0

Silver Cow Party POJ - 3268

One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1…N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.
Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow’s return route might be different from her original route to the party since roads are one-way.
Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?

Input

Line 1: Three space-separated integers, respectively: N, M, and X

Lines 2…M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and
Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.

Output

Line 1: One integer: the maximum of time any one cow must walk.
Sample Input
4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3

Sample Output
10

Hint

Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.

题意
求X到某点来回路程的最短路的最大值。

题解
X到某点的最短路可以由dijkstra算法求得,但是某点回来的路程需要对每个点都使用dijkstra算法,时间复杂度过大。
逆向思维:返程为往程的逆过程。
此时,只需要使用两次dijkstra算法就可以了。

代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
#include <vector>
#define P pair<int, int>
using namespace std;
const int MAX = 1e3 + 2;
const int INF = 0x3f3f3f3f;struct edge{
    int to, cost;
};int N, M, X;
vector<edge>G1[MAX];//往
vector<edge>G2[MAX];//返
int d1[MAX], d2[MAX];
void dijkstra (int d[],vector <edge>G[]) {
    priority_queue<P, vector<P>, greater<P> > que;fill(d, d + N, INF);d[X - 1] = 0;que.push(P(0, X - 1));while(que.size()) {
    P p = que.top(); que.pop();int v = p.second;if(d[v] < p.first) continue;for(int i = 0; i < G[v].size(); i++) {
    edge e = G[v][i];if(d[v] + e.cost < d[e.to]) {
    d[e.to] = d[v] + e.cost;que.push(P(d[e.to], e.to));}}}
}int main() {
    scanf("%d%d%d", &N, &M, &X);for(int i = 0; i < M; i++) {
    int a, b, t;scanf("%d%d%d", &a, &b, &t);a--, b--;edge e1, e2;e1.to = b, e1.cost = t;e2.to = a, e2.cost = t;G1[a].push_back(e1);G2[b].push_back(e2);}dijkstra(d1, G1);dijkstra(d2, G2);int ans = 0;for(int i = 0; i < N; i++)ans = max (ans, (d1[i] + d2[i]));printf("%d\n", ans);
}
  相关解决方案