SPFA算法,求两次最短路:
// ShellDawn
// POJ3268
// No.11
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#define MM(x) memset(x,0,sizeof(x))
#define MMF(x) memset(x,0x3f,sizeof(x))
#define INF 0x3f3f3f3f
#define NINF 0xc0c0c0c0
using namespace std;
#define maxn 1005
int n,m,s;
// 邻接表
int EA[maxn][maxn][2];
int cntA[maxn];
int EB[maxn][maxn][2];
int cntB[maxn];
// end
int ansA[maxn];
int ansB[maxn];
void SPFA(int ans[maxn],int E[maxn][maxn][2],int cnt[maxn]){
queue<int> q;
ans[s] = 0;
q.push(s);
while(!q.empty()){
int loc = q.front();
q.pop();
for(int i=0;i<cnt[loc];i++){
int next = E[loc][i][0];
int v = E[loc][i][1];
if(ans[loc] + v < ans[next]){
ans[next] = ans[loc] + v;
q.push(next);
}
}
}
}
int main(){
//freopen("A.txt","r",stdin);
while(~scanf("%d%d%d",&n,&m,&s)){
MM(EA);MM(EB);MM(cntA);MM(cntB);
for(int i=0;i<m;i++){
int a,b,c;
cin>>a>>b>>c;
int loc = cntA[a];
EA[a][loc][0] = b;
EA[a][loc][1] = c;
cntA[a] ++;
loc = cntB[b];
EB[b][loc][0] = a;
EB[b][loc][1] = c;
cntB[b] ++;
}
MMF(ansA);
SPFA(ansA,EA,cntA);
MMF(ansB);
SPFA(ansB,EB,cntB);
int ans = 0;
for(int i=1;i<=n;i++){
if(i==s) continue;
ans = max(ans,ansA[i] + ansB[i]);
}
cout<<ans<<endl;
}
return 0;
}