题目描述

题解思路
参考https://www.acwing.com/solution/content/9306/
参考https://www.acwing.com/solution/content/21057/
代码
cpp
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 100010;
int n, m, a, b, c, idx;
int h[N], ne[N], e[N], w[N], dist[N];
bool vis[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);
dist[1] = 0;
queue<int>q;
q.push(1);
vis[1] = true;
while (q.size())
{
int t = q.front();
q.pop();
vis[t] = false; // 从队列中取出来之后该节点st被标记为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 (!vis[j]) // 当前已经加入队列的结点,无需再次加入队列,即便发生了更新也只用更新数值即可,重复添加降低效率
{
q.push(j);
vis[j] = true;
}
}
}
}
if (dist[n] == 0x3f3f3f3f) return 0;
return dist[n];
}
int main()
{
memset (h, -1, sizeof h);
cin >> n >> m;
while (m -- )
{
cin >> a >> b >> c;
add(a, b, c);
}
int t = spfa();
if (t == 0) puts("impossible");
else cout << t;
return 0;
}
