poj 3268 Silver Cow Party

来源:互联网 发布:如何克隆淘宝店铺 编辑:程序博客网 时间:2024/04/30 10:30
Silver Cow Party
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 10102 Accepted: 4489

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 ≤XN). A total ofM (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; roadi requiresTi (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, andX
Lines 2..M+1: Line i+1 describes road i with three space-separated integers:Ai,Bi, andTi. The described road runs from farmAi to farmBi, requiringTi 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

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.

题意:一个有向图,求每个点:到终点的距离+终点到该点的距离,从中找出最大值。
思路:求终点到每个点的距离用一次dij就可以求出,但是求每个点到终点的距离时,如果进行n次dij,则会TLE。解决方法是先在原图上用一次dij求出终点到每个点的距离,然后在反图上再用一次dij求出终点到每个点的距离。这样只用了两次dij。

AC代码:
#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <algorithm>#include <queue>#include <cmath>#include <vector>#include <cstdlib>using namespace std;const int INF=10000000;int n,x;int map[1005][1005];int dis[1005];bool vis[1005];int back[1005];     //保存回去时终点到各点的最短距离int go[1005];       //保存各点到终点的最短距离void dij(int d[]){    memset(vis,false,sizeof(vis));    for(int i=1;i<=n;i++)    dis[i]=map[x][i];    vis[x]=true;    for(int i=1;i<=n;i++)    {        int x,min=INF;        for(int j=1;j<=n;j++)        if(!vis[j]&&dis[j]<min)        min=dis[x=j];        if(min==INF) break;        vis[x]=true;        for(int j=1;j<=n;j++)        if(!vis[j]&&dis[j]>dis[x]+map[x][j])            dis[j]=dis[x]+map[x][j];    }    for(int i=1;i<=n;i++)    d[i]=dis[i];}int main(){   int m,a,b,t;   while(scanf("%d%d%d",&n,&m,&x)!=EOF)   {       for(int i=1;i<=n;i++)       for(int j=1;j<=n;j++)       {           if(i==j) map[i][j]=0;           else           map[i][j]=INF;       }       while(m--)       {           scanf("%d%d%d",&a,&b,&t);           map[a][b]=t;       }       dij(back);       for(int i=1;i<=n;i++)       //将矩阵转置       for(int j=i+1;j<=n;j++)       {           int temp=map[i][j];           map[i][j]=map[j][i];           map[j][i]=temp;       }       dij(go);       int max=0;       for(int i=1;i<=n;i++)       {           if(back[i]+go[i]>max)           max=back[i]+go[i];       }       printf("%d\n",max);   }   return 0;}


原创粉丝点击