POJ No.3255 Roadblocks 求次短路径

时间:2023-01-01 00:26:07
 #define _CRT_SECURE_NO_WARNINGS
/*
7 10
0 1 5
0 2 2
1 2 4
1 3 2
2 3 6
2 4 10
3 5 1
4 5 3
4 6 5
5 6 9 4 4
0 1 100
1 3 200
1 2 250
2 3 100
*/
#include <iostream>
#include <functional>
#include <utility>
#include <queue>
#include <vector>
using namespace std; const int maxn = + ;
const int INF = ;
typedef pair<int, int> P; //first-最短距离,second-顶点编号
struct edge
{
int to, cost;
}; //输入
int N, R; //N-点,R-边
vector<edge> G[maxn]; //图的邻接表表示 int dist[maxn]; //最短距离
int dist2[maxn]; //次短距离 void solve()
{
priority_queue<P, vector<P>, greater<P> > que;
fill(dist, dist + N, INF);
fill(dist2, dist2 + N, INF);
dist[] = ;
que.push(P(, )); while (!que.empty())
{
P p = que.top(); que.pop(); //队列存放 (最短路和次短路)
int v = p.second, d = p.first;
if (dist2[v] < d) continue; //如果次小的值小,跳过该值
for (int i = ; i < G[v].size(); i++) {
edge &e = G[v][i]; //得到v的临边
int d2 = d + e.cost; //d2 = 已知最短或次短 + 临边权值
if (dist[e.to] > d2) { //如果未确定的最短路 > d2
swap(dist[e.to], d2);
que.push(P(dist[e.to], e.to)); //添加最短路
}
if (dist2[e.to] > d2 && dist[e.to] < d2) {
dist2[e.to] = d2; //说明d2是次大值
que.push(P(dist2[e.to], e.to)); //添加次短路
}
}
}
printf("%d\n", dist2[N - ]); //N位置的dist2即为
} void input()
{
int from, to, cost;
edge tmp;
for (int i = ; i < R; i++) {
cin >> from >> to >> cost;
tmp.to = to; tmp.cost = cost;
G[from].push_back(tmp);
tmp.to = from;
G[to].push_back(tmp);
}
} int main()
{
cin >> N >> R;
input();
solve();
return ;
}