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
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
輸出說明:
最短路: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[n].second);
return 0;
}