白书上题
求次短路问题:
code:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include<cmath>
#include<cstdlib>
#include<map>
#include<string>
#include<vector>
#include<queue>
#include<functional>
#pragma warning(disable:4996)
using namespace std;
typedef long long ll;
typedef pair<int, int>P;//first是最短路径,second是顶点编号
const int INF = 0x7fffffff;
int d[100010];
int dist2[100010];
int n, r;
struct edge {
int to, cost;
};
int V;//顶点
vector<edge>G[100010];//vectoe存图
void build_map(int r)
{
int i, j,s,t,k;
for (i = 1; i <=r; i++)
{
edge e,ee;
scanf("%d %d %d",&s,&t,&k);
e.to = s; e.cost = k;
G[t].push_back(e);
ee.to = t; ee.cost = k;
G[s].push_back(ee);
}
}
void dijkstra(int s)
{
//通过指定<greater>参数,按照first从小到大的顺序取出值
priority_queue< P, vector<P>, greater<P> >que;
for (int i = 1; i <= n; i++)
{
d[i] = INF;
dist2[i] = INF;
}
d[s] = 0;//d[v]表示从起始节点到该节点的最小权值也可以说是最短路径
que.push(P(0, s));//把起始节点存入队列g
//整体思想有点类似贪心
while (!que.empty())
{
P p = que.top();
que.pop();
int v = p.second;
if (dist2[v] < p.first)
continue;//如果比当前此段路长 continue
for (int i = 0; i < G[v].size(); i++)
{
edge e = G[v][i];
int d2 =p.first+ e.cost;//d2可以是最短路径
if (d[e.to] > d2)
{
swap(d[e.to],d2);
que.push(P(d[e.to], e.to));
}
if (dist2[e.to] > d2&&d[e.to]<d2)//保证次短路是小于最短路的
{
dist2[e.to] = d2;
que.push( P(dist2[e.to], e.to) );
}
}
}
}
int main()
{
scanf("%d %d", &n, &r);
for (int i = 1; i <= n; i++)
G[i].clear();
build_map(r);
dijkstra(1);
printf("%d\n", dist2[n]);
return 0;
}