题目描述
给定一个 n个点 m条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你求出 1号点到 n号点的最短距离,如果无法从 1号点走到 n号点,则输出 impossible。数据保证不存在负权回路。
样例
输入样例:
3 3
1 2 5
2 3 -3
1 3 4
输出样例:
2
算法1
(spfa)
时间复杂度 o(m) 最坏o(nm)
参考文献
spfa算法框架:
*** queue里面存的是待更新的点
queue <- 1
while queue不空 (一般用队列)
1. 取出队头t
q.pop();
2.更新t的所有出边 t到b距离w
queue <- b
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
int h[N], ne[N], e[N], w[N], idx;
int dist[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c,ne[idx] = h[a], h[a] = idx ++;
}
/*
spfa算法框架:
*** queue里面存的是待更新的点
queue <- 1
while queue不空 (一般用队列)
1. 取出队头t
q.pop();
2.更新t的所有出边 t到b距离w
queue <- b
*/
int spfa()
{
queue<int> q;
q.push(1);
st[1] = true;
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; 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.push(j);
}
}
}
}
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);
}
if (spfa() == 0x3f3f3f3f) puts("impossible");
else cout << spfa();
return 0;
}