G. Silver Cow Party
One cow from each ofNfarms (1 ≤N≤ 1000) conveniently numbered 1..Nis going to attend the big cow party to be held at farm #X(1 ≤X≤N). A total ofM(1 ≤M≤ 100,000) unidirectional (one-way roads connects pairs of farms; roadirequiresTi(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
Lines 2.. M+1: Line i+1 describes road iwith three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Aito farm Bi, requiring Titime units to traverse.
Output
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
这道题其实是一道最短路的变形。在建图的时候正反各建立一次,然后用spfa求得相应的距离。
这里要注意一下,以后建图的时候尽可能用邻接表来建立。(可以用数组,可以用vector、list)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#define INF 10000000
using namespace std;
int n,m,x,dist_v1[1010]= {0},dist_v2[1010]= {0};
struct node
{
int x,d;
};
vector<node> v1[1010];
vector<node> v2[1010];
void spfa_v1(int x)
{
int i,j,visit[1010]= {0},t;
queue<int> q;
for (i=1; i<=n; i++)
dist_v1[i]=INF;
dist_v1[x]=0;
visit[x]=1;
q.push(x);
int s,l;
while(!q.empty())
{
t=q.front();
q.pop();
visit[t]=0;
for (i=0; i<v1[t].size(); i++)
{
s=v1[t][i].x;
l=v1[t][i].d;
if (dist_v1[s]>dist_v1[t]+l)
{
dist_v1[s]=dist_v1[t]+l;
if (!visit[s])
{
visit[s]=1;
q.push(s);
}
}
}
}
}
void spfa_v2(int x)
{
int i,j,visit[1010]= {0},t;
queue<int> q;
for (i=1; i<=n; i++)
dist_v2[i]=INF;
dist_v2[x]=0;
visit[x]=1;
q.push(x);
int s,l;
while(!q.empty())
{
t=q.front();
q.pop();
visit[t]=0;
for (i=0; i<v2[t].size(); i++)
{
s=v2[t][i].x;
l=v2[t][i].d;
if (dist_v2[s]>dist_v2[t]+l)
{
dist_v2[s]=dist_v2[t]+l;
if (!visit[s])
{
visit[s]=1;
q.push(s);
}
}
}
}
}
int main ()
{
int i,j;
int a,b,t;
scanf("%d%d%d",&n,&m,&x);
node e;
while(m--)
{
scanf("%d%d%d",&a,&b,&t);
e.x=b;
e.d=t;
v1[a].push_back(e);
e.x=a;
v2[b].push_back(e);
}
spfa_v1(x);
spfa_v2(x);
int max=0,s1,s2;
for (i=1; i<=n; i++)
{
if (max<dist_v1[i]+dist_v2[i])
max=dist_v1[i]+dist_v2[i];
}
cout<<max<<endl;
return 0;
}