次短路
基础例题:https://vjudge.net/problem/POJ-3255
之前已经说过dijkstra算法是依次确定距离操作点最近的顶点,依据这个算出来的当然是最短路径,那么次短路径肯定不能是这条路径,所以至少有一条边不是最短路线上的
dijkstra提供了一个很巧妙的算法,本来只用一个d数组记录最短路径,现在改用两个数组,一个记录最短路,另一个记录次短路,然后接下来做法大致相同,算法复杂度还是不变的(O(E*logV))有一些细节还是想了好久。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#define ll long long
#define pb push_back
using namespace std;
const int maxn=6000;
const int INF=0x3fffffff;
typedef pair<int,int > P;
struct edge
{
int from,to,cost;
edge(int t,int c)
{
to=t;
cost=c;
}
};
vector<edge> G[maxn];//图的邻接表表示
int d1[maxn];//最短路径
int d2[maxn];//次短路径
int n,m,x,y,w;
void solve(int n)
{
priority_queue<P,vector<P>,greater<P> > q;
fill(d1,d1+n,INF);
fill(d2,d2+n,INF);
d1[0]=0;
q.push(P(0,0));//起点
while(!q.empty())
{
P p=q.top();
q.pop();
int v=p.second,d=p.first;
if (d2[v]<d)
continue;//如果次短路径比最短路径短,那么显然是矛盾的
for (int i=0; i<G[v].size(); i++)
{
edge &e=G[v][i];
int x=d+e.cost;
if (d1[e.to]>x)//更新最短路径,并加入队列继续往下
{
swap(d1[e.to],x);//为什么不写成下面这个式子呢?因为既然d1[e.to]不是最短路径,那么它还是有可能会作为次短路径一部分的,所以有必要更新数值然后接着判断
//****d1[e.to]=x;
q.push(P(d1[e.to],e.to));
}
if (d2[e.to]>x&&d1[e.to]<x)//更新次短路径,并加入队列继续往下
{
d2[e.to]=x;
q.push(P(d2[e.to],e.to));
}
}
}
cout<<d2[n-1]<<endl;
}
int main()
{
cin>>n>>m;
for (int i=0; i<m; i++)
{
cin>>x>>y>>w;
x--;
y--;
G[x].pb(edge(y,w));
G[y].pb(edge(x,w));
}
solve(n);
}
暂时只学了这个方法,感觉很神奇o