Silver Cow Party POJ

来源:互联网 发布:网站域名未授权 编辑:程序博客网 时间:2024/05/18 01:54

Description

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: NM, and X 
Lines 2..M+1: Line i+1 describes road i with three space-separated integers: AiBi, 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 21 2 41 3 21 4 72 1 12 3 53 1 23 4 44 2 3

Sample Output

10


思路:这个题其实只要变换一下思路就会变得十分简单,其余的所有奶牛从自己编号的位置到s去,在回家。选出来回走的路最多的奶牛。因为这是一个有向图,所以到s去不就相当于把所有的路径都反向储存然后从s到其余的各个奶牛。

这样处理会使时间复杂度大大减低,从而得出答案。

PS:第一次用优先队列写,还不是很熟练,要多加练习,其次就是把算法自定义为一个函数确实会使代码风格更加的精炼,下面附上代码。

#include <iostream>#include <vector>#include <string>#include <algorithm>#include <queue>#include <stack>#include <cstdio>#define MXAN 2010#define INF 1 << 27using namespace std;struct edge{    int to;    int cost;    bool operator < (const edge & a) const {        if (cost == a.cost)            return to < a.to;        else            return cost > a.cost;    }};int n, m, des;void Dijkstra(int s, vector<edge> vec[], int dis[]) {    int i;    for (i = 1; i <= n; ++i)        dis[i] = INF;    dis[s] = 0;    priority_queue<edge> q;    q.push(edge{s, dis[s]});    while (!q.empty()) {        edge x = q.top();        q.pop();        for (i = 0; i < vec[x.to].size(); ++i) {            edge y = vec[x.to][i];            if (dis[y.to] > x.cost + y.cost) {                dis[y.to] = x.cost + y.cost;                q.push(edge{y.to, dis[y.to]});            }        }    }}int main(){    while(~scanf("%d%d%d", &n, &m, &des)){        vector<edge> G1[MXAN];        vector<edge> G2[MXAN];        int a, b, c;        for(int i = 0; i < m; ++i){            scanf("%d%d%d", &a, &b, &c);            G1[a].push_back(edge{b, c});            G2[b].push_back(edge{a, c});        }        int dis1[MXAN], dis2[MXAN];        Dijkstra(des, G1, dis1);        Dijkstra(des, G2, dis2);        int max_length = 0;        for(int i = 1; i <= n; ++i){            max_length = max(max_length, dis1[i] + dis2[i]);        }        printf("%d\n", max_length);    }    return 0;}


0 0
原创粉丝点击