POJ 3268 Silver Cow Party
最短路水题,正向边,反向边各跑一次。
#include<cstdio> #include<cstring> #include<cmath> #include<queue> #include<vector> #include<algorithm> using namespace std; const int INF=0x7FFFFFFF; const int maxn=1000+10; int n,m,x; int dis1[maxn],dis2[maxn]; struct Edge { int to,val; }e1[110000],e2[110000]; int tot; vector<int>g1[maxn],g2[maxn]; int flag[maxn]; void SPFA1() { for(int i=1;i<=n;i++) dis1[i]=INF; queue<int>Q; memset(flag,0,sizeof flag); dis1[x]=0,flag[x]=1; Q.push(x); while(!Q.empty()) { int head=Q.front(); Q.pop(); flag[head]=0; for(int i=0;i<g1[head].size();i++) { int id=g1[head][i]; if(dis1[head]+e1[id].val<dis1[e1[id].to]) { dis1[e1[id].to]=dis1[head]+e1[id].val; if(flag[e1[id].to]==0) { flag[e1[id].to]=1; Q.push(e1[id].to); } } } } } void SPFA2() { for(int i=1;i<=n;i++) dis2[i]=INF; queue<int>Q; memset(flag,0,sizeof flag); dis2[x]=0,flag[x]=1; Q.push(x); while(!Q.empty()) { int head=Q.front(); Q.pop(); flag[head]=0; for(int i=0;i<g2[head].size();i++) { int id=g2[head][i]; if(dis2[head]+e2[id].val<dis2[e2[id].to]) { dis2[e2[id].to]=dis2[head]+e2[id].val; if(flag[e2[id].to]==0) { flag[e2[id].to]=1; Q.push(e2[id].to); } } } } } int main() { scanf("%d%d%d",&n,&m,&x); tot=0; for(int i=1;i<=m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); tot++; e1[tot].to=v,e1[tot].val=w; g1[u].push_back(tot); e2[tot].to=u,e2[tot].val=w; g2[v].push_back(tot); } SPFA1(); SPFA2(); int ans=0; for(int i=1;i<=n;i++) { if(dis1[i]==INF||dis2[i]==INF) continue; if(i==x) continue; ans=max(ans,dis1[i]+dis2[i]); } printf("%d\n",ans); return 0; }