AcWing 851. spfa求最短路
原题链接
简单
作者:
尽量不说话
,
2021-02-21 18:04:39
,
所有人可见
,
阅读 303
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int>PII;
const int N = 250010;
int n, m;
int h[N], w[N], e[N], ne[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 sofa()
{
queue<int>q;
memset(dist, 0x3f, sizeof (dist));
dist[1] = 0;
st[1] = true;
q.push(1);
while(q.size())
{
auto 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])
{
q.push(j);
st[j] = true;
}
}
}
}
if(dist[n] == 0x3f3f3f3f)
return -1;
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(sofa() == -1)
cout << "impossible" << endl;
else
cout << sofa()<<endl;
}