求最短路

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, INF = 0x3f3f3f3f;
int n, m, d[N];
bool st[N];
vector < pair<int, int> > g[N];
void spfa(){
	memset(d, 0x3f, sizeof d);
	d[1] = 0;
	queue <int> q;
	q.push(1);
	st[1] = true;
	while (q.size()){
		int u = q.front();
		q.pop();
		st[u] = false;
		for (auto t : g[u]){
			int v = t.first, w = t.second;
			if (d[v] > d[u] + w){
				d[v] = d[u] + w;
				if (!st[v]){
					q.push(v);
					st[v] = true;
				}
			}
		}
	}
	if (d[n] == INF) cout << "impossible\n";
	else cout << d[n] << "\n";
}
int main(){
	cin >> n >> m;
	for (int i = 1; i <= m; i ++ ){
		int u, v, w;
		cin >> u >> v >> w;
		g[u].push_back({v, w});
	}
	spfa();
	return 0;
}

acwing 模板:https://www.acwing.com/problem/content/853/

判断负环

luogu 模板题

#include <bits/stdc++.h>
using namespace std;
const int N = 2e3 + 10, INF = 0x3f3f3f3f;
int T, n, m, d[N], cnt[N];
vector < pair <int, int> > g[N];
bool st[N];
void spfa(){
	queue <int> q;
	q.push(1);
	d[1] = 0;
	st[1] = true;
	while (q.size()){
		int u = q.front();
		q.pop();
		st[u] = false;
		for (auto t : g[u]){
			int v = t.first, w = t.second;
			if (d[v] > d[u] + w){
				d[v] = d[u] + w;
				cnt[v] = cnt[u] + 1;
				if (cnt[v] >= n){
					cout << "YES\n";
					return;
				}
				if (!st[v]){
					q.push(v);
					st[v] = true;
				}
			}
		}
	}
	cout << "NO\n";
}
void Clear(){
	for (int i = 1; i <= n; i ++ ){
		g[i].clear();
		st[i] = false;
		d[i] = INF;
		cnt[i] = 0;
	}
}
void solve(){
	cin >> n >> m;
	Clear();
	for (int i = 1; i <= m; i ++ ){
		int u, v, w;
		cin >> u >> v >> w;
		g[u].push_back({v, w});
		if (w >= 0) g[v].push_back({u, w});
	}
	spfa();
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	cin >> T;
	while (T--)
		solve();
	return 0;
}

acwing 模板:https://www.acwing.com/problem/content/854/
luogu 模板:https://www.luogu.com.cn/problem/P3385

posted on 2022-04-18 21:18  Hamine  阅读(28)  评论(0编辑  收藏  举报