Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 15106 | Accepted: 6821 |
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
原题
或见图论算法理论171页
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#define M1 1010
#define M2 100100
#define INF 999999999
using namespace std;
struct ArcNode{
int to,weight;
ArcNode *next;
};
ArcNode *list1[M1];//入边表
ArcNode *list2[M1];//出边表
bool inq[M1];
int dist1[M1],dist2[M1],dist[M1];
int n,m,x;
queue<int>q;
void SPFA(int x){
int i,u;
ArcNode *temp;
for(i=1;i<=n;i++){
dist1[i]=INF;
inq[i]=false;
}
dist1[x]=0;inq[x]=true;
q.push(x);
while(!q.empty()){
u=q.front();q.pop();inq[u]=false;
temp=list1[u];
while(temp!=NULL){
int v=temp->to;
if(dist1[v]>dist1[u]+temp->weight){
dist1[v]=dist1[u]+temp->weight;
if(!inq[v]){
q.push(v);inq[v]=true;
}
}
temp=temp->next;
}
}
for(i=1;i<=n;i++){
dist2[i]=INF;
inq[i]=false;
}
dist2[x]=0;inq[x]=true;
q.push(x);
while(!q.empty()){
u=q.front();q.pop();inq[u]=false;
temp=list2[u];
while(temp!=NULL){
int v=temp->to;
if(dist2[v]>dist2[u]+temp->weight){
dist2[v]=dist2[u]+temp->weight;
if(!inq[v]){
q.push(v);inq[v]=true;
}
}
temp=temp->next;
}
}
}
int main(int argc, char *argv[])
{
while(cin>>n>>m>>x){
int i,u,v,w;
ArcNode *temp;
memset(list1,0,sizeof(list1));
memset(list1,0,sizeof(list2));
for(i=0;i<m;i++){
scanf("%d%d%d",&u,&v,&w);
temp = new ArcNode;
temp->to=u;temp->weight=w;temp->next=NULL;
if(list1[v]==NULL) list1[v]=temp;
else {temp->next=list1[v];list1[v]=temp;}
temp = new ArcNode;
temp->to=v;temp->weight=w;temp->next=NULL;
if(list2[u]==NULL) list2[u]=temp;
else {temp->next=list2[u];list2[u]=temp;}
}
SPFA(x);
//释放空间
for(i=1;i<=n;i++){
temp=list1[i];
while(temp!=NULL){
list1[i]=temp->next;delete temp;temp=list1[i];
}
temp=list2[i];
while(temp!=NULL){
list2[i]=temp->next;delete temp;temp=list2[i];
}
}
int ma=0;
for(i=1;i<=n;i++){
dist[i]=dist1[i]+dist2[i];
if(dist[i]>ma) ma=dist[i];
}
cout<<ma<<endl;
}
return 0;
}