适用

有负环的优先用spfa算法

讲解

这个用到了一个思想,就是一个数只有前面的数更新了,那么它才能更新。
1,用邻接表存储。
2,队列中存的是更新过的点。
3,判断的时候这个表状态的st数组是干什么的呢?
其实这就是判断了一下这个更新的数是否已经在队列中了,提高一下效率,我们只要判断哪个节点更新过了就行。
4,注意更新的时候是加上w[i]而不是w[j]因为i才是指针,j是节点的编号。
4,最后别忘了返回dist[n]

源码

#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 10;

int n, m;
int dist[N];
int h[N], e[N], ne[N], w[N], idx;
bool st[N];

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

int spfa()
{
	memset(dist, 0x3f, sizeof dist);

	queue<int> q;
	dist[1] = 0;
	q.push(1);
	while(q.size())
	{
		int t = q.front();
		q.pop();

		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])
				{
					q.push(j);
					st[j] = true;
				}
			}
		}
	}

	return dist[n];
}



int main()
{
	cin >> n >> m;
	memset(h, -1, sizeof h);

	while(m -- )
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}

	int res = spfa();

	if (res == 0x3f3f3f3f) cout << "impossible" << endl;
	else cout << dist[n];
}