poj 3255 次短路演算法(好)
阿新 • • 發佈:2019-01-04
題意:給你n個點,m條邊,然後問你從1到n的次短路是多少(比最短路長,比其他路都短的路)
題解:看書上用dij非常複雜,然後百度到了一個不錯的題解,用spfa,先算出每個點到1的最短路dis[i],再算出每個點到n點的最短路disr[i]
然後列舉m條邊,計算次短路dis[u]+disr[v]+edge[u][v]
#include <map> #include <set> #include <stack> #include <queue> #include <cmath> #include <string> #include <vector> #include <cstdio> #include <cctype> #include <cstring> #include <sstream> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; #define MAX 5005 #define MAXN 205 #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define lrt rt<<1 #define rrt rt<<1|1 #define mid int m=(r+l)>>1 #define LL long long #define ull unsigned long long #define mem0(x) memset(x,0,sizeof(x)) #define mem1(x) memset(x,-1,sizeof(x)) #define meminf(x) memset(x,INF,sizeof(x)) #define lowbit(x) (x&-x) const int mod = 1000000007; const int prime = 999983; const int INF = 0x3f3f3f3f; const int INFF = 1e9; const double pi = 3.141592653589793; const double inf = 1e18; const double eps = 1e-10; struct Edge{ int v,cost,next; }edge[200005]; int head[MAX]; int dis[MAX]; int disr[MAX]; int vis[MAX]; int tot; int n,m; void add_edge(int a,int b,int c){ edge[tot]=(Edge){b,c,head[a]}; head[a]=tot++; } void spfa(int u,int d[]){ mem0(vis); queue<int> q; q.push(u); vis[u]=1; d[u]=0; while(!q.empty()){ u=q.front(); q.pop(); vis[u]=0; for(int i=head[u];i!=-1;i=edge[i].next){ int v=edge[i].v; int cost=edge[i].cost; if(d[v]>d[u]+cost){ d[v]=d[u]+cost; if(!vis[v]){ vis[v]=1; q.push(v); } } } } } int main(){ scanf("%d%d",&n,&m); mem1(head); meminf(dis); meminf(disr); int tot=0; for(int i=0;i<m;i++){ int a,b,c; scanf("%d%d%d",&a,&b,&c); add_edge(a,b,c); add_edge(b,a,c); } spfa(1,dis); spfa(n,disr); int mini=dis[n]; int ans=INF; for(int i=1;i<=n;i++){ for(int j=head[i];j!=-1;j=edge[j].next){ int v=edge[j].v; int cost=edge[j].cost; if(dis[i]+disr[v]+cost>mini&&dis[i]+disr[v]+cost<ans) ans=dis[i]+disr[v]+cost; } } printf("%d\n",ans); return 0; }