题目入口
题意:给定一个n个点m条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出impossible。数据保证不存在负权回路。
输入格式
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式
输出一个整数,表示1号点到n号点的最短距离。
如果路径不存在,则输出”impossible”。
数据范围
1≤n,m≤10^5,
图中涉及边长绝对值均不超过10000。
输入样例:
3 3
1 2 5
2 3 -3
1 3 4
输出样例:
2
思路:
原理:其实就是bellman-ford的优化,长得像Dijkstra.
- bellman-ford算法在每次迭代都要遍历每一条边来更新dist[b] = min(dist[b],dist[a] + w),但有些边其实也不会被更新。
- 而spfa就是用一个队列来做,想把起点加入队列q,之后只要q不空就取出队头t,并pop()掉t,再遍历t的出边t -> b = w,如若dist[b]被更新并不存在队列q中就加入q。(说简单点就是用更新过的边t去更新和t有关的边,省去了无用的遍历)
代码实现:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define lowbit(x) (x &(-x))
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double EXP = 1e-8;
const ll MOD = 1e9 + 7;
const int N = 1e6 + 5;
int n, m;
int h[N], e[N], ne[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 ++;
}
int spfa()
{
mem(dist, 0x3f);
dist[1] = 0;
st[1] = 1;
queue<int> q;
q.push(1);
while(q.size()){
int t = q.front(); q.pop();
st[t] = 0;
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] = 1;
}
}
}
}
if(dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
signed main()
{
IOS;
cin >> n >> m;
mem(h, -1);
while(m --){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
int ans = spfa();
if(ans == -1) puts("impossible");
else cout << ans << endl;
return 0;
}