spfa

发布时间 2023-04-19 16:23:40作者: lfyszy

无负环

#include <bits/stdc++.h>
#define PII pair<int, int>

using namespace std;

const int N = 1e5 + 10;

int e[N], ne[N], h[N], w[N], idx;

void add(int a, int b, int c)
{
	e[++ idx] = b;
	w[idx] = c;
	ne[idx] = h[a];
	h[a] = idx;
}

bool st[N];
PII q[N];
int dist[N], n, m;

void spfa()
{
	memset(dist, 0x3f, sizeof dist);
	int hh = 0, tt = -1;
	q[++ tt] = {0, 1};
	dist[1] = 0;
	
	while(hh <= tt)
	{
		auto p = q[hh ++];
		int t = p.second;
		st[t] = false;	
		for(int i = h[t]; ~i; i = ne[i])
		{
			int j = e[i];
			if(dist[j] > dist[t] + w[i])
			{
				dist[j] = dist[t] + w[i];
				if(!st[j])
				{
					st[j] = true;
					q[++ tt] = {dist[j], j};
				}
			}
		}
	}
	
	if(dist[n] == 0x3f3f3f3f) cout << "impossible\n";
	else cout << dist[n] << "\n";	
}

int main()
{
	memset(h, -1, sizeof h);
	
	cin >> n >> m;
	
	for(int i = 1; i <= m; i ++)
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}
	
	spfa();
	
	return 0;
}