Roadblocks
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 22083 | Accepted: 7677 |
Description
Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
Input
Line 1: Two space-separated integers: N and R
Lines 2..R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)
Output
Line 1: The length of the second shortest path between node 1 and node N
Sample Input
4 4
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
450
题目大意 : 输入一个无向图,输出次短路大小。
思路 : 次短路就是排序后在最短路后面的那个值,求次短路的关键就在于他的数值比最短路小一个级别,比其他任意的路径都要大某个级别,所以在更新路径的过程中,需要再维护一个dis【】数组,表示次短路。
AC代码 :
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 1e6 + 5;
const int INF = 0x3f3f3f3f;
struct node
{
int v, w, next;
}e[maxn];
struct edge
{
int id, w;
bool operator < (const edge &oth) const
{
return w > oth.w;
}
}mid;
int head[maxn], dis1[maxn], dis2[maxn], n, m, cnt;
priority_queue <edge> q;
void add (int from, int to, int dis) {
e[++cnt].v = to;
e[cnt].w = dis;
e[cnt].next = head[from];
head[from] = cnt;
}
void dijkstra(int u) {
memset(dis1, INF, sizeof(dis1));
memset(dis2, INF, sizeof(dis2));
dis1[u] = 0;
q.push({u, 0});
while (!q.empty()) {
mid = q.top();
q.pop();
int ans = mid.id;
if (dis2[ans] < mid.w) continue; //次短路要大于等于最短路
for (int i = head[ans]; i != -1; i = e[i].next) {
int vi = e[i].v, wi = mid.w + e[i].w;
if (dis1[vi] > wi) {
swap (dis1[vi], wi);
q.push({vi, dis1[vi]});
}
if (dis1[vi] <= wi && dis2[vi] >= wi) { //次短路在最短路与其他路径之间
dis2[vi] = wi;
q.push({vi, dis2[vi]});
}
}
}
}
int main()
{
cin >> n >> m;
memset(head, -1, sizeof(head));
for (int i = 0; i < m; i++) {
int ui, vi, wi;
cin >> ui >> vi >> wi;
add (ui, vi, wi);
add (vi, ui, wi);
}
dijkstra(1);
cout << dis2[n] << endl;
return 0;
}