AcWing 851. spfa求最短路
原题链接
简单
作者:
dsyami
,
2021-06-05 11:12:02
,
所有人可见
,
阅读 175
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
int h[N], e[N], ne[N], w[N], idx;
int n, m;
int dist[N];
bool st[N];
void add(int a, int b, int z)
{
e[idx] = b; w[idx] = z; ne[idx] = h[a]; h[a] = idx ++;
}
int spfa()
{
queue<int> q;
q.push(1);
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
st[1] = true;
while (q.size())
{
int k = q.front(); q.pop();
st[k] = false;
for (int i = h[k]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[k] + w[i])
{
dist[j] = dist[k] + w[i];
if (!st[j])
{
st[j] = true;
q.push(j);
}
}
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
else return dist[n];
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
while (m -- )
{
int x, y, z;
cin >> x >> y >> z;
add(x, y, z);
}
int ans = spfa();
if (ans == -1) puts("impossible");
else cout << ans << endl;
return 0;
}