差分约束练习

这篇文章介绍了如何使用C++编程语言实现SPFA(最短路径优先搜索)算法,用于求解带权图中的最短路径问题,包括数据结构定义、函数实现和流程控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <bits/stdc++.h>
using namespace std;


inline int read(int& x) {
	char ch = getchar();
	int f = 1; x = 0;
	while (ch > '9' || ch < '0') { if (ch == '-')f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); }
	return x * f;
}
//void ReadFile() {
//	FILE* stream1;
//	freopen_s(&stream1,"in.txt", "r", stdin);
//	freopen_s(&stream1,"out.txt", "w", stdout);
//}

static auto speedup = []() {ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return nullptr; }();

const int maxn = 5e3 + 7,INF = 1e9 + 7;
int n, m,dis[maxn],vis[maxn],cnt[maxn];
vector<pair<int,int>> e[maxn];

bool spfa(int cur) {
	for (int i = 0; i <= n; i++) { dis[i] = INF; vis[i] = 0; }
	dis[cur] = 0;
	queue<int> q;
	q.push(cur);
	while (!q.empty()) {
		int top = q.front(); q.pop();
		vis[top] = 0;
		for (auto& point : e[top]) {
			int nx = point.first, v = point.second;
			if (dis[nx] > dis[top] + v) {
				dis[nx] = dis[top] + v;
				if (cnt[nx] >= n) return false;
				if (!vis[nx]) {
					vis[nx] = 1;
					cnt[nx]++;
					q.push(nx);
				}
			}
		}
	}
	return true;
}

void slove() {
	cin >> n >> m;
	int a, b, c;
	for (int i = 1; i <= m; i++) {
		cin >> a >> b >> c;
		e[b].push_back({ a,c });
	}
	for (int i = 1; i <= n; i++) {
		e[0].push_back({i,0});
	}
	if (!spfa(0)) {
		cout << "NO" << endl;
	}
	else {
		for (int i = 1; i <= n; i++) {
			cout << dis[i] << " ";
		}
		cout << endl;
	}
}
int main() {
	slove();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值