最短路,使用两次Dijkstra算法,只是注意回来的时候起点和终点就好。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define INF 1000000
using namespace std;
int mingo[1005];
int minback[1005];
int cost[1005][1005];
int judge[1005];
int n,m,target;
void dijgo(int u){
for(int i=1;i<=n;i++) mingo[i]=cost[i][u];
judge[u]=1;
for(int num=1;num<n;num++){
int k=-1;
int min=INF;
for(int i=1;i<=n;i++){
if(judge[i]==0&&min>mingo[i]){
min=mingo[i];
k=i;
}
//if(judge[i]==0) v=i;
}
if(k==-1) break;
judge[k]=1;
for(int i=1;i<=n;i++){
if(judge[i]==0&&mingo[i]>mingo[k]+cost[i][k]){
mingo[i]=mingo[k]+cost[i][k];
}
}
//printf("yes\n");
}
return ;
}
void dijback(int u){
for(int i=1;i<=n;i++) minback[i]=cost[u][i];
judge[u]=1;
for(int num=1;num<n;num++){
int k=-1;
int min=INF;
for(int i=1;i<=n;i++){
if(judge[i]==0&&min>minback[i]){
min=minback[i];
k=i;
}
}
//if(k==-1) break;
judge[k]=1;
for(int i=1;i<=n;i++){
if(judge[i]==0&&minback[i]>minback[k]+cost[k][i]){
minback[i]=minback[k]+cost[k][i];
}
}
//printf("%d %d\n",k,minback[k]);
}
return ;
}
int main(){
int x,y,v;
while(scanf("%d%d%d",&n,&m,&target)!=EOF){
for(int i=1;i<=n;i++){
mingo[i]=INF;
minback[i]=INF;
for(int j=1;j<=n;j++){
if(i==j) cost[i][j]=0;
else
cost[i][j]=INF;
}
}
for(int i=0;i<m;i++){
scanf("%d%d%d",&x,&y,&v);
cost[x][y]=v;
}
//printf("%d %d %d %d\n",cost[4][2],cost[2][1],cost[1][3],cost[3][4]);
memset(judge,0,sizeof(judge));
dijgo(target);
memset(judge,0,sizeof(judge));
dijback(target);
int max=-1;
for(int i=1;i<=n;i++){
//printf("%d %d\n",mingo[i],minback[i]);
if(max<mingo[i]+minback[i]&&i!=target) max=mingo[i]+minback[i];
}
printf("%d\n",max);
}
return 0;
}