思路:
(1)存图:由于是稀疏图,故用邻接表存储,w[]同步存权值
(2)由于带负权求最短路,于是考虑spfa()算法,st[]同步标记是否在队列中。
(3)spfa算法:
- 初始化,dist[]初始化为无穷,起点初始化为0,队列里放入起点,起点设为在队列中。
- 不断拿出队头元素t,并标记为不在队列里,遍历与t相连的所有节点j,如果能缩短更新距离,就更新距离;更新后如果j不在队列中,就放在队列中以备用。
- 最后判定,如果dist[n] == 0x3f3f3f3f即未被更新过,则为不可达;反之则为可达。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 150000;
int n,m;
int h[N],st[N],e[N],ne[N],idx,dist[N],w[N];
typedef pair<int,int> PII;
void add(int a,int b,int c)
{
e[idx] = b,ne[idx] = h[a],w[idx] = c,h[a] = idx ++;
}
void spfa()
{
memset(dist,0x3f,sizeof dist);
dist[1] = 0;
queue<int> q;
q.push(1);
while(!q.empty())
{
auto t = q.front();
q.pop();
st[t] = 0;
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] = 1;
}
}
}
}
if(dist[n] == 0x3f3f3f3f) puts("impossible");
else
cout << dist[n] << endl;
}
int main()
{
memset(h,-1,sizeof h);
cin >> n >> m;
while(m --)
{
int a,b,c;
cin >> a >> b >> c;
add(a,b,c);
}
spfa();
return 0;
}