跳到正文

休闲·娱乐

关于用dijkstra过了负环这一块

Frilen约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年11月12日
收录
2026年9月9日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

rt代码如下

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long

const int N=2e3;

int t,n,m,s;
vector<pair<int,int>>edge[N+5];
priority_queue<pair<pair<int,int>,int>,vector<pair<pair<int,int>,int>>,greater<pair<pair<int,int>,int>>>pq;
queue<pair<pair<int,int>,int>>q;
int d[N+5];

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> t;
//	t = 1;
	while(t--)
	{
		cin >> n >> m;
		s=1;
//		cin >> s;
		for(int i = 1;i <= n;i++)
		{
			edge[i].clear();
			d[i] = 1e18;
		}
		while(!pq.empty()) pq.pop();
		while(!q.empty())q.pop();
		for(int i = 1;i <= m;i++)
		{
			int u,v,w;
			cin >> u>>v>>w;
			edge[u].push_back({v,w});
			if(w >= 0)edge[v].push_back({u,w});
		}
		pq.push({{0,0},s});
		bool f = 1;
		for(int i = 1;i<=n+1;i++)
		{
			while(!q.empty())
			{
				auto p=q.front();
				q.pop();
				pq.push(p);
			}
			while(!pq.empty())
			{
				if(!f)break;
				auto p = pq.top();
				int k = pq.top().first.first;
				int cnt = pq.top().first.second;
				int now = pq.top().second;
				pq.pop();
				if(cnt>i)
				{
					q.push(p);
					continue;
				}
				if(k > d[now]) continue;
				for(auto p:edge[now])
				{
					int ne = p.second;
					int to = p.first;
					if(ne+k<d[to]) 
					{
						d[to]=ne+k;
						pq.push({{ne+k,cnt+1},to});
						if(cnt>n)
						{
							f=0;
							break;
						}
					}
				}
			}
		}
		if(f)cout<<"NO\n";
		else cout <<"YES\n";
//		for(int i = 1;i<=n;i++)cout<<d[i]<<' ';
	}
	return 0;
}

顺便一提这个代码改下格式可以过单源最短路
通过记录(负环)通过记录(单源最短路)

原文