poj3255 次短路的长度
这道问题是求1-N的次短路的长度,我们直接在dist[maxn][2]上加1维更新即可, 代码如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <queue> using namespace std; const int maxn = 5000 + 10; int N, R; struct edge { int v, c; }; vector<edge> G[maxn]; struct Dij { int u, flog, c; bool operator< (const Dij& r) const { return c > r.c; } }; int dist[maxn][2], vis[maxn][2]; void dijkstra() { memset(dist, 0x3f, sizeof(dist)); memset(vis, 0, sizeof(vis)); dist[1][0] = 0; priority_queue<Dij> que; que.push((Dij){1, 0, 0}); while(!que.empty()) { Dij tp = que.top(); que.pop(); int u=tp.u, flog=tp.flog; if(vis[u][flog]) continue; vis[u][flog] = 1; for(int i=0; i<G[u].size(); i++) { int v = G[u][i].v, c = G[u][i].c; int w = dist[u][flog] + c; if(w < dist[v][0]) //更新次短路 最短路 { if(dist[v][0] != 0x3f3f3f3f) { dist[v][1] = dist[v][0]; que.push((Dij){v, 1, dist[v][1]}); } dist[v][0] = w; que.push((Dij){v, 0, dist[v][0]}); } else if(w<dist[v][1]) //更新次短路 { dist[v][1] = w; que.push((Dij){v, 1, dist[v][1]}); } } } } int main() { scanf("%d%d", &N, &R); for(int i=0; i<R; i++) { int u, v, c; scanf("%d%d%d", &u, &v, &c); G[u].push_back((edge){v, c}); G[v].push_back((edge){u, c}); } dijkstra(); printf("%d\n", dist[N][1]); return 0; }