POJ 3255Roadblocks

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

这一题求的是次短路,就算是迪杰斯特拉的一个变形,最短路可以用迪杰斯特拉求出来,那么次短路呢?这种涉及到距离更新的最好用SPFA算法,即用优先队列优化过的算法,更新时有天然的优势。那么这边与一般的最短路算法不同,这边要存最短路d1与次短路d2,再更新d1或d2。因为关键只有一句,就是此点的次短路一定是由邻接点的最短路或次短路变化而来,所以现在是要不断更新最短路与次短路。



AC代码:


# include <cstdio>
# include <queue>
using namespace std;
typedef long long int LL;
const LL inf=20000000000000;
struct edge{
	int to;
	int cost;
};
struct p{
	LL d;
	int u;
	bool operator <(const p &rch)const{
		return d>rch.d;
	}
};
vector<edge> g[5010];
priority_queue<p> q;
LL d1[5010];
LL d2[5010];
int main(){
	int i, j, k, n, r, x, y, d, te;
	int num1, num2, num3;
	p temp;
	edge e;
	while(scanf("%d%d", &n, &r)!=EOF){
		for(i=1; i<=n; i++){
			g[i].clear();
		}
		for(i=1; i<=r; i++){
			scanf("%d%d%d", &num1, &num2, &num3);
			e.cost=num3;e.to=num2;
			g[num1].push_back(e);
			e.cost=num3;e.to=num1;
			g[num2].push_back(e);
		}
		while(!q.empty()){
			q.pop();
		}
		for(i=1; i<=n; i++){
			d1[i]=d2[i]=inf;
		}
		d1[1]=0;
		temp.d=0;
		temp.u=1;
		q.push(temp);
		while(!q.empty()){
			temp=q.top();q.pop();
			x=temp.u;y=temp.d;
			if(y>d2[x]){
				continue;
			}
			for(i=0; i<=g[x].size()-1; i++){
				e=g[x][i];
				d=y+e.cost;
				if(d1[e.to]>d){
					te=d;d=d1[e.to];d1[e.to]=te;
					temp.d=d1[e.to];
					temp.u=e.to;
					q.push(temp);
				}
				if(d1[e.to]<d&&d2[e.to]>d){
					d2[e.to]=d;
					temp.d=d2[e.to];
					temp.u=e.to;
					q.push(temp);
				}
			}
		}
		printf("%lld\n", d2[n]);
	}
	return 0;
}


你可能感兴趣的:(ACM,优先队列,poj,SPFA,迪杰斯特拉)