[hihocode#1093] 最短路径·三:SPFA算法

题目来源:http://hihocoder.com/problemset/problem/1093
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
万圣节的晚上,小Hi和小Ho在吃过晚饭之后,来到了一个巨大的鬼屋!

鬼屋中一共有N个地点,分别编号为1..N,这N个地点之间互相有一些道路连通,两个地点之间可能有多条道路连通,但是并不存在一条两端都是同一个地点的道路。

不过这个鬼屋虽然很大,但是其中的道路并不算多,所以小Hi还是希望能够知道从入口到出口的最短距离是多少?

提示:Super Programming Festival Algorithm。
输入
每个测试点(输入文件)有且仅有一组测试数据。

在一组测试数据中:

第1行为4个整数N、M、S、T,分别表示鬼屋中地点的个数和道路的条数,入口(也是一个地点)的编号,出口(同样也是一个地点)的编号。

接下来的M行,每行描述一条道路:其中的第i行为三个整数u_i, v_i, length_i,表明在编号为u_i的地点和编号为v_i的地点之间有一条长度为length_i的道路。

对于100%的数据,满足N<=105,M<=106, 1 <= length_i <= 10^3, 1 <= S, T <= N, 且S不等于T。

对于100%的数据,满足小Hi和小Ho总是有办法从入口通过地图上标注出来的道路到达出口。

输出
对于每组测试数据,输出一个整数Ans,表示那么小Hi和小Ho为了走出鬼屋至少要走的路程。

样例输入
5 10 3 5
1 2 997
2 3 505
3 4 118
4 5 54
3 5 480
3 4 796
5 2 794
2 5 146
5 4 604
2 5 63
样例输出
172

由于数据比较大,N<=105,M<=106,不能使用邻接矩阵,使用邻接表存图,最短路算法可以采用堆优化dijkstra,模板题。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+1;
const int INF = 1e9+1;
struct edge{
	int from, to, cost;
};
vector <edge> G[maxn];
int n, m, s, t, d[maxn];
bool vis[maxn];
typedef pair<int, int> P;

void dijkstra(int s){
	priority_queue <P, vector<P>, greater<P> > q;
	fill(d, d+maxn, INF);
	memset(vis, false, sizeof(vis));
	d[s] = 0;
	q.push((P){d[s], s});
	while(!q.empty()){
		P u = q.top();
		q.pop();
		int v = u.second;
		if(vis[v])
			continue;
		vis[v] = true;
		for(int i=0; i<G[v].size(); i++){
			edge e = G[v][i];
			if(d[v]<INF && d[e.to]>d[v]+e.cost){
				d[e.to] = d[v]+e.cost;
				q.push((P){d[e.to], e.to});
			}
		}
	}
}

int main(){
	scanf("%d %d %d %d", &n, &m, &s, &t);
	for(int i=1; i<=m; i++){
		int x, y, z;
		scanf("%d %d %d", &x, &y, &z);
		G[x].push_back((edge){x, y, z});
		G[y].push_back((edge){y, x, z});
	}
	dijkstra(s);
	printf("%d", d[t]);
	return 0;
}

另外还可以使用队列优化的Bellman-Ford算法,即SPFA,模板题。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+1;
const int INF = 1e9+1;
struct edge{
	int from, to, cost;
};
vector <edge> G[maxn];
int n, m, s, t, d[maxn], num[maxn];
bool inque[maxn];
queue <int> q;

bool spfa(int s){
	fill(d, d+maxn, INF);
	memset(inque, false, sizeof(inque));
	memset(num, 0, sizeof(num));
	d[s] = 0;
	q.push(s);
	num[s] = 1;
	inque[s] = true;
	while(!q.empty()){
		int u = q.front();
		q.pop();
		inque[u] = false;
		for(int i=0; i<G[u].size(); i++){
			edge e = G[u][i];
			if(d[u]<INF && d[e.to]>d[u]+e.cost){
				d[e.to] = d[u]+e.cost;
				if(!inque[e.to]){
					q.push(e.to);
					inque[e.to] = true;
					if(++num[e.to]>n){ // 有负环 
						return true;
					}
				}
			}
		} 
	}
	return false;
}

int main(){
	scanf("%d %d %d %d", &n, &m, &s, &t);
	for(int i=1; i<=m; i++){
		int x, y, z;
		scanf("%d %d %d", &x, &y, &z);
		G[x].push_back((edge){x, y, z});
		G[y].push_back((edge){y, x, z});
	}
	if(spfa(s) || d[t]==INF) // 有负环或无法走到 
		printf("circle\n"); 
	else
		printf("%d", d[t]);
	return 0;
}
posted @ 2019-09-16 16:52  gdgzliu  阅读(395)  评论(0编辑  收藏  举报