您的位置:首页 > 其它

POJ - 3268 Silver Cow Party(图论/dijkstra最短路)

2017-04-24 20:09 513 查看
问题描述

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

分析:

神奇的一题。

代码如下:

#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstring>
const int maxn = 1000+10;
const int maxe = 100000+10;
const int INF = 10000000;
using namespace std;
struct edge{
int to,cost;
edge(int to, int cost):to(to), cost(cost){}
};

typedef pair<int, int> P;
int N, M, X;
vector<vector<edge> > G(maxn);
vector<vector<edge> > BG(maxn);
int d[maxn];//d[i]为点i到party点并返回的距离和最小
int b_d[maxn];

void dijkstra(int s)
{
priority_queue<P,vector<P>,greater<P> > q;
fill(d, d + N, INF);
d[s] = 0;
q.push(P(0,s));

while(!q.empty())
{
P p = q.top(); q.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[e.to] > d[v] + e.cost)
{
d[e.to] = d[v] + e.cost;
q.push(P(d[e.to],e.to));
}
}
}
}

int main()
{
scanf<
c906
/span>("%d%d%d",&N, &M, &X);
int a,b,t;
--X;
for(int i=0; i<M; i++)
{
scanf("%d%d%d",&a,&b,&t);
--a;
--b;
G[a].push_back(edge(b, t));
BG[b].push_back(edge(a, t));
}
dijkstra(X);

G = BG;
memcpy(b_d, d, sizeof(d));
dijkstra(X);

for(int i=0; i<N; i++)
{
d[i] += b_d[i];
}
int m = 0;
for(int i=0; i<N; i++)
{
m = max(m, d[i]);
}
printf("%d\n",m);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: