您的位置:首页 > 编程语言 > C语言/C++

BZOJ 1726: [Usaco2006 Nov]Roadblocks第二短路

2014-08-31 15:22 267 查看

1726: [Usaco2006 Nov]Roadblocks第二短路

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

输出说明:

最短路:1 -> 2 -> 4 (长度为100+200=300)

第二短路:1 -> 2 -> 3 -> 4 (长度为100+250+100=450)

——分割线——

这道题、、大概就是一个SPFA记录下最大和次大路径就可以、

【诶,这道题目,我的更新判定写错了,一直Wa,结果太自信已知没检查更新判断,所以死成渣了、、、

代码:

#include<cstdio>
#include<queue>
using namespace std;
const int inf=100000000;
struct DistNode{
int first;
int second;
DistNode(){first=inf/10;second=inf;}
bool update(DistNode x,int dist){
bool flag=false;
if(x.first+dist<first){
second=min(first,x.second+dist);
first=x.first+dist;
flag=true;
}else if((x.first+dist>first)&&(x.first+dist<second)){
second=x.first+dist;
flag=true;
}else if((x.first+dist==first)&&(x.second+dist<second)){
second=x.second+dist;
flag=true;
}
return flag;
}
};

DistNode dist[5010];
struct EdgeNode{
int to;
int dist;
int nxt;
EdgeNode(){}
EdgeNode(int a,int b,int c){
to=a;
dist=b;
nxt=c;
}
};
EdgeNode edge[200010];
int nume=0;
int head[5010];
inline void insertEdge(int x,int y,int w){
edge[++nume]=EdgeNode(y,w,head[x]);
head[x]=nume;
edge[++nume]=EdgeNode(x,w,head[y]);
head[y]=nume;
}

queue<int> que;
bool inQue[5010];
inline void bfs(){
while(!que.empty()) que.pop();
que.push(1);
inQue[1]=true;
dist[1].first=0;
//dist[1].second=0;

while(!que.empty()){
int index=que.front();
que.pop();inQue[index]=false;
for (int i=head[index];i;i=edge[i].nxt){
int goal=edge[i].to;
int fare=edge[i].dist;
if (dist[goal].update(dist[index],fare)){
if (inQue[goal]==false){
inQue[goal]=true;
que.push(goal);
}
}
}
}
}

int n,r;
int main(){
scanf("%d%d",&n,&r);
for (int i=1;i<=r;i++){
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
insertEdge(x,y,w);
}

bfs();

printf("%d\n",dist
.second);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  题解 OI C++ BZOJ 1726