长的有点像dijkstra的Bellman_Ford算法的优化版 SPFA
作者:
呆比小昱
,
2021-12-15 16:31:20
,
所有人可见
,
阅读 257
SPFA算法(用队列优化的Bellman_Ford算法)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;
int n, m;
int e[N], ne[N], h[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()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
queue<int> q;
q.push(1);
st[1] = true;
while(q.size())
{
int 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;
}
}
}
}
return dist[n];
}
int main()
{
memset(h, -1, sizeof h);
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i ++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
int res = spfa();
if (res == 0x3f3f3f3f) puts("impossible");
else printf("%d\n", res);
return 0;
}
姐姐巨!QWQ
弟弟多大了呀
姐姐巨!QWQ
嘻嘻