AcWing 851. spfa求最短路
原题链接
简单
作者:
芝居気
,
2021-12-05 19:23:35
,
所有人可见
,
阅读 117
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define db(x) cout<<#x<<" = "<<x<<". ";
int n, m;
const int N = 100005;
int e[N], ne[N], h[N], idx;
int w[N];
bool st[N];
int dis[N];
void add(int a, int b, int c)
{
w[idx] = c;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void spfa()
{
memset(dis,0x3f,sizeof(dis));
dis[1] = 0;
queue<int> q;
q.push(1);
st[1] = 1;
while (q.size())
{
int temp = q.front();
//db(temp) cout<<endl;
q.pop();
st[temp] = 0;
for (int i = h[temp]; ~i; i = ne[i])
{
int j = e[i];
if (dis[j] > dis[temp] + w[i]) //也就比广搜多了这两行,判断入列条件从全入变成了距离缩短的且没在队列的入
{
dis[j] = dis[temp] + w[i];
if (!st[j])
{
q.push(j);
st[j] = 1;
}
}
}
}
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b, c;
add(a, b, c);
}
spfa();
if (dis[n] != 0x3f3f3f3f) cout <<dis[n];
else cout << "impossible";
}