1726: [Usaco2006 Nov]Roadblocks第二短路
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 1324 Solved: 627
[ Submit][ Status][ Discuss]
Description
贝茜把家搬到了一个小农场,但她常常回到FJ的农场去拜访她的朋友。贝茜很喜欢路边的风景,不想那么快地结束她的旅途,于是她每次回农场,都会选择第二短的路径,而不象我们所习惯的那样,选择最短路。 贝茜所在的乡村有R(1<=R<=100,000)条双向道路,每条路都联结了所有的N(1<=N<=5000)个农场中的某两个。贝茜居住在农场1,她的朋友们居住在农场N(即贝茜每次旅行的目的地)。 贝茜选择的第二短的路径中,可以包含任何一条在最短路中出现的道路,并且,一条路可以重复走多次。当然咯,第二短路的长度必须严格大于最短路(可能有多条)的长度,但它的长度必须不大于所有除最短路外的路径的长度。
Input
* 第1行: 两个整数,N和R,用空格隔开
* 第2..R+1行: 每行包含三个用空格隔开的整数A、B和D,表示存在一条长度为 D(1 <= D <= 5000)的路连接农场A和农场B
Output
* 第1行: 输出一个整数,即从农场1到农场N的第二短路的长度
Sample Input
4 4
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
450
直接套模板http://blog.youkuaiyun.com/jaihk662/article/details/77688996
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define inf 1044266558
int n, m, k, s, t;
int head[5010], bet[5010], vis[5010], cnt, cnt2;
typedef struct Edge
{
int to, c;
int next;
}Edge;
Edge G[200050];
void Add(int a, int b, int c)
{
cnt++;
G[cnt].next = head[a];
head[a] = cnt;
G[cnt].to = b;
G[cnt].c = c;
}
queue<int> q;
typedef struct Res
{
int f; //f是估价函数,等于d加上从x到终点T的最短路
int x, d; //x是当前到达的点,d表示从起点s到x总共走的路程
bool operator < (const Res &b) const //队列的顶端f最小
{
if(f>b.f)
return 1;
return 0;
}
}Res;
Res u, v;
priority_queue<Res> vq;
void Solve()
{
int i, tc;
u.f = bet[s], u.x = s, u.d = 0;
vq.push(u);
while(vq.empty()==0)
{
u = vq.top();
vq.pop();
if(u.x==t && u.d!=bet[s])
{
printf("%d\n", u.d);
return;
}
for(i=head[u.x];i;i=G[i].next)
{
tc = G[i].to;
v = u;
v.x = tc, v.d += G[i].c, v.f = bet[v.x]+v.d;
vq.push(v);
}
}
printf("-1\n");
}
int main(void)
{
int i, x, y, c;
while(scanf("%d%d", &n, &m)!=EOF)
{
memset(head, 0, sizeof(head));
cnt = cnt2 = 0;
for(i=1;i<=m;i++)
{
scanf("%d%d%d", &x, &y, &c);
Add(x, y, c);
Add(y, x, c);
}
s = 1, t = n, k = 2;
if(s==t)
k++;
memset(bet, 62, sizeof(bet));
memset(vis, 0, sizeof(vis));
bet[t] = 0, vis[t] = 1;
q.push(t);
while(q.empty()==0)
{
x = q.front();
q.pop();
vis[x] = 0;
for(i=head[x];i;i=G[i].next)
{
y = G[i].to;
if(bet[y]>bet[x]+G[i].c)
{
bet[y] = bet[x]+G[i].c;
if(vis[y]==0)
{
q.push(y);
vis[y] = 1;
}
}
}
}
if(bet[s]==inf)
printf("-1\n");
else
{
Solve();
while(vq.empty()==0)
vq.pop();
}
}
}
/*
2 1
1 2 100
*/