90分,SPFA求调
查看原帖
90分,SPFA求调
167697
BartAllen楼主2023/1/11 15:51
#include <bits/stdc++.h>
using namespace std;

const int N = 1e4 + 5;
const int M = 5e5 + 5;

int n, m, s, tot;
int head[N], ver[M], edge[M], Next[M], d[N];
queue<int> q;
bool v[N];

void add(int x, int y, int z) {
	ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;
}

void spfa() {
	memset(d, 0x3f, sizeof(d));
	d[s] = 0, v[s] = 1;
	q.push(s);
	while (!q.empty()) {
		int x = q.front(); q.pop();
		v[x] = 0;
		for (int i = head[x]; i; i = Next[i]) {
			int y = ver[i], z = edge[i];
			if (d[y] > d[x] + z) {
				d[y] = d[x] + z;
				if (!v[y]) q.push(y), v[y] = 1;
			}
		}
	}
}

int main() {
	cin >> n >> m >> s;
	for (int i = 1; i <= m; i++) {
		int x, y, z;
		cin >> x >> y >> z;
		add(x, y, z);
	}
	spfa();
	for (int i = 1; i <= n; i++) cout << d[i] << " ";
	cout << endl;
	return 0;
}
2023/1/11 15:51
加载中...