图论 - 最短路 - SPFA

图论 - 最短路 - SPFA

题目链接:https://www.luogu.org/problem/P3371

代码:

#include <bits/stdc++.h>

using namespace std;

const int N = 10010;

const int M = 500050;

int n, m, s, dis[N];

int tot, head[N], to[M], nxt[M], val[M];

bool vis[N];

void add(int x, int y, int z) {
	to[ ++ tot] = y;
	nxt[tot] = head[x];
	val[tot] = z;
	head[x] = tot;	
}

void Spfa(int x) {
	memset(dis, 0x3f, sizeof dis);
	memset(vis, 0, sizeof vis);
	queue <int> q;
	dis[x] = 0;
	vis[x] = 1;
	q.push(x);
	while (! q.empty()) {
		int now = q.front();
		q.pop();
		vis[now] = 0;
		for (int i = head[now]; i; i = nxt[i]) {
			if (dis[to[i]] > dis[now] + val[i]) {
				dis[to[i]] = dis[now] + val[i];
				q.push(to[i]);
				vis[to[i]] = 1;
			}
		}
	}
}

int main() {
	scanf("%d%d%d", &n, &m, &s);
	for (int i = 1; i <= m; i ++ ) {
		int x, y, z;
		scanf("%d%d%d", &x, &y, &z);
		add(x, y, z);
	}
	Spfa(s);
	for (int i = 1; i <= n; i ++ ) {
		if (dis[i] == 0x3f3f3f3f) {
			dis[i] = 2147483647;
		}
		printf("%d ", dis[i]);
	}
	return 0;
}

SPFA优化:

#include <bits/stdc++.h>

using namespace std;

const int N = 10100;

const int M = 500500;

int n, m, s, dis[N];

int tot, head[N], to[M], nxt[M], val[M];

bool vis[N];

void add(int x, int y, int z) {
	to[ ++ tot] = y;
	nxt[tot] = head[x];
	val[tot] = z;
	head[x] = tot;	
}

deque <int> q;

void Spfa(int x) {
	memset(dis, 0x3f, sizeof dis);
	memset(vis, 0, sizeof vis);
	dis[x] = 0;
	vis[x] = 1;
	q.push_front(x);
	while (! q.empty()) {
		int now = q.front();
		q.pop_front();
		vis[now] = 0;
		for (int i = head[now]; i; i = nxt[i]) {
			if (dis[to[i]] > dis[now] + val[i]) {
				dis[to[i]] = dis[now] + val[i];
				if(! vis[to[i]]) {   
					vis[to[i]] = 1;
					if (q.empty() || dis[to[i]] <= dis[q.front()]) {
						q.push_front(to[i]);
					}
					else {
						q.push_back(to[i]);
					}
				}
			}
		}
	}
}

int main() {
	scanf("%d%d%d", &n, &m, &s);
	for (int i = 1; i <= m; i ++ ) {
		int x, y, z;
		scanf("%d%d%d", &x, &y, &z);
		add(x, y, z);
	}
	Spfa(s);
	for (int i = 1; i <= n; i ++ ) {
		if (dis[i] == 0x3f3f3f3f) {
			dis[i] = 2147483647;
		}
		printf("%d ", dis[i]);
	}
	return 0;
}
posted @ 2019-11-14 10:08  筱柒_Littleseven  阅读(80)  评论(0编辑  收藏  举报