您的位置:首页 > 其它

poj3255 Roadblocks (次短路)

2017-08-18 19:48 155 查看
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

思路:

我们枚举每条边,对于一条边的u,v,w我们计算从1到(u|v)的最短路加边权加(v|u)到n的最短路。然后如果这个值比1-n的最短路要大,就更新答案。

详细的可以看这里

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;
typedef long long LL;
const int MAXN = 5e3+5;
const int inf = 1e9;
int n,m;
struct node
{
int v,w;
node(int a,int b)
{
v = a;
w = b;
}
};
vector<node>head[MAXN];
bool vis[MAXN];
int dis_s[MAXN],dis_t[MAXN];
void spfa(int s,int *dis)
{
for(int i = 1; i <= n; ++i)
{
vis[i] = 0;
dis[i] = inf;
}
deque<int>q;
q.push_back(s);
dis[s] = 0;
int cnt = 1,sum = 0;
while(!q.empty())
{
int u = q.front();
q.pop_front();
if(dis[u]*cnt > sum)
{
q.push_back(u);
continue;
}
vis[u] = 1;
cnt--,sum -= dis[u];
for(int i = 0, l = head[u].size(); i < l; ++i)
{
int v = head[u][i].v;
int w = head[u][i].w;
if(dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
if(!vis[v])
{
vis[v] = 1;
cnt++,sum += dis[v];
if(q.empty() || dis[v] > dis[q.front()])q.push_back(v);
else q.push_front(v);
}
}
}
}
}

int u[100000],v[100000],w[100000];
int main()
{
scanf("%d%d",&n,&m);
for(int i = 0; i < m; ++i)
{
scanf("%d%d%d",&u[i],&v[i],&w[i]);
head[u[i]].push_back(node(v[i],w[i]));
head[v[i]].push_back(node(u[i],w[i]));
}
spfa(1,dis_s);
spfa(n,dis_t);
int ans = inf;
for(int i = 0; i < m; ++i)
{
int temp = dis_s[u[i]] + w[i] + dis_t[v[i]];
if(temp > dis_s
&& temp < ans)ans = temp;
temp = dis_s[v[i]] + w[i] + dis_t[u[i]];
if(temp > dis_s
&& temp < ans)ans = temp;
}
printf("%d\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: