bzoj1726[Usaco2006 Nov]Roadblocks第二短路*

bzoj1726[Usaco2006 Nov]Roadblocks第二短路

题意:

求无向图点1到n的次短路(长度严格小于最短路)。点数≤5000,边数≤100000。

题解:

求源点为1的单源最短路和源点为n的单源最短路。然后枚举每个点,如果某点到点1和点n的距离和不等于1到n的最短路距离且最小则答案为它。

代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <queue>
 5 #define inc(i,j,k) for(int i=j;i<=k;i++)
 6 #define maxn 5010
 7 #define INF 0x3fffffff
 8 using namespace std;
 9 
10 inline int read(){
11     char ch=getchar(); int f=1,x=0;
12     while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
13     while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
14     return f*x;
15 }
16 struct e{int f,t,w,n;}es[maxn*40]; int g[maxn],ess,d[2][maxn],n,m; bool inq[maxn]; queue<int>q;
17 void pe(int f,int t,int w){es[++ess]=(e){f,t,w,g[f]}; g[f]=ess; es[++ess]=(e){t,f,w,g[t]}; g[t]=ess;}
18 void spfa(int s,bool a){
19     while(!q.empty())q.pop(); memset(inq,0,sizeof(inq)); inc(i,1,n)d[a][i]=INF;
20     q.push(s); inq[s]=1; d[a][s]=0;
21     while(!q.empty()){
22         int x=q.front(); q.pop(); inq[x]=0;
23         for(int i=g[x];i;i=es[i].n)if(d[a][es[i].t]>d[a][x]+es[i].w){
24             d[a][es[i].t]=d[a][x]+es[i].w;
25             if(!inq[es[i].t])q.push(es[i].t),inq[es[i].t]=1;
26         }
27     }
28 }
29 int main(){
30     n=read(); m=read(); inc(i,1,m){int a=read(),b=read(),c=read(); pe(a,b,c);}
31     spfa(1,0); spfa(n,1); int mn=INF;
32     inc(i,1,ess){
33         if(d[0][es[i].f]+es[i].w+d[1][es[i].t]<mn&&d[0][es[i].f]+es[i].w+d[1][es[i].t]!=d[0][n])
34             mn=d[0][es[i].f]+es[i].w+d[1][es[i].t];
35     }
36     printf("%d",mn); return 0;
37 }

 

20160907

原文地址:https://www.cnblogs.com/YuanZiming/p/5861969.html