关于用 dijkstra 做最长路引出的一些问题
  • 板块学术版
  • 楼主Zhang_Wenjie
  • 当前回复8
  • 已保存回复8
  • 发布时间2023/8/14 10:54
  • 上次更新2023/11/3 03:57:00
查看原帖
关于用 dijkstra 做最长路引出的一些问题
481621
Zhang_Wenjie楼主2023/8/14 10:54
  1. dij 可以在全负权边图中跑最长路吗?

  2. dij 对每个点只松弛一次,如果我把 vis 判断去掉,复杂度会有多劣?

  3. 如果CCF的比赛中有个图论题,但标算不是 dij,对于该题应当给出数据是否有重边吗?

  4. 为什么这种玄学代码能过 P1807 最长路?

甚至 w∈[−105,105]w\in[-10^5,10^5] qwq

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, int> pli;
const int N = 1510, M = 5e4 + 10, R = 1e5 + 1;
const ll inf = LLONG_MAX;
struct edge
{
	int to, next;
	ll w;
}e[M];
int top, h[N], cnt[N], n, m;
ll dist[N];
bool vis[N];
priority_queue< pli, vector<pli> > q;

void add(int x, int y, ll w)
{
	e[++top].to = y;
	e[top].w = w;
	e[top].next = h[x];
	h[x] = top;
}

void dijkstra(int s)
{
	for (int i = 1; i <= n; i ++) dist[i] = -inf;
	dist[s] = 0;
	q.push({0ll, s});
	while (!q.empty())
	{
		int x = q.top().second;
		q.pop();
//		if (vis[x]) continue; 
//		vis[x] = true;
		for (int i = h[x]; i ; i = e[i].next)
		{
			int y = e[i].to;
			ll w = e[i].w;
			if (dist[x] + w > dist[y])
			{
				dist[y] = dist[x] + w;
				cnt[y] = cnt[x] + 1;
				q.push({dist[y], y});
			}
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	
	cin >> n >> m;
	for (int i = 1; i <= m; i ++)
	{
		int x, y;
		ll w;
		cin >> x >> y >> w;
		add(x, y, w);
	}
	dijkstra(1);
	cout << (dist[n] == -inf ? -1 : dist[n]);
	
	return 0;
}
2023/8/14 10:54
加载中...