Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 27217 | Accepted: 12436 |
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
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
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
思路:两个最短路即可。牛往回走,其实就相当与把原来的有向图的边全部反过来!! 明白了这点就很容易做了
#include "iostream" #include "queue" #include "algorithm" #include "cstring" using namespace std; const int Max=1005; const int inf=0xfffffff; int G1[Max][Max],G2[Max][Max];//分别正向建边,和反向建边 int d1[Max],d2[Max];//分别记录正,反向建边,从农场x到其他农场的最权值 int n,e,s; struct edge { int to,cost; friend bool operator <(edge a,edge b){return a.cost<b.cost;} }; void dijk() { priority_queue<edge> que1; priority_queue<edge> que2; fill(d1,d1+n+1,inf); fill(d2,d2+n+1,inf); d1[s]=d2[s]=0; edge e1,e2; e1.to=e2.to=s; e1.cost=e2.cost=0; que1.push(e1); que2.push(e2); while(!que1.empty()){//正向最短路 e1=que1.top(); que1.pop(); int u=e1.to; for(int i=1;i<=n;i++){ int v=G1[u][i]; if(v!=0&&d1[i]>d1[u]+v){ d1[i]=d1[u]+v; e1.to=i; e1.cost=d1[i]; que1.push(e1); } } } while(!que2.empty()){//逆向最短路 e2=que2.top(); que2.pop(); int u=e2.to; for(int i=1;i<=n;i++){ int v=G2[u][i]; if(v!=0&&d2[i]>d2[u]+v){ d2[i]=d2[u]+v; e2.to=i; e2.cost=d2[i]; que2.push(e2); } } } } int main() { int u,v,w; ios::sync_with_stdio(false); while(cin>>n>>e>>s){ memset(G1,0, sizeof(G1)); memset(G2,0, sizeof(G2)); for(int i=0;i<e;i++){ cin>>u>>v>>w; G1[u][v]=w; G2[v][u]=w; } dijk(); int ans=0; for(int i=1;i<=n;i++){ ans=max(ans,d1[i]+d2[i]); } cout<<ans<<endl; } }