题目链接:http://poj.org/problem?id=3255
题意:给你一个图,由n个点,m条无向边构成,让你找一条从顶点1到顶点n的次短路出来,次短路是指比最短路长的次短的路径
解析:假设求到一个顶点v的次短路,那么肯定会有两种情况,一种就是到某个顶点u的最短路加上u->v的这条边,还有一种情况就是到u的次短路,加上u->v的这条边,所以用dj跑的时候,开了两个数组,一个记录最短路,一个记录次短路。
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 2e5+100;
const int inf = 0x7fffffff;
struct node
{
int v,w;
node() {}
node(int _v,int _w)
{
v = _v;
w = _w;
}
bool operator < (const node &b)const
{
return w>b.w;
}
};
vector<node>G[maxn];
int dis[maxn];
int ans[maxn];
int n,m;
void dijkstra()
{
fill(dis,dis+n+1,inf);
fill(ans,ans+n+1,inf);
dis[1] = 0;
priority_queue<node>q;
q.push(node(1,0));
while(!q.empty())
{
node now = q.top();
q.pop();
for(int i=0;i<G[now.v].size();i++)
{
node tmp = G[now.v][i];
int d = now.w+tmp.w;
if(dis[tmp.v]>d)
{
swap(d,dis[tmp.v]);
q.push(node(tmp.v,dis[tmp.v]));
}
if(ans[tmp.v]>d && dis[tmp.v]<d)
{
ans[tmp.v] = d;
q.push(node(tmp.v,d));
}
}
}
printf("%d\n",ans[n]);
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++)
{
int u,v,w;
scanf("%d %d %d",&u,&v,&w);
G[u].push_back(node(v,w));
G[v].push_back(node(u,w));
}
dijkstra();
return 0;
}