题目:
给定一个 nn 个点 mm 条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你求出 11 号点到 nn 号点的最短距离,如果无法从 11 号点走到 nn 号点,则输出 impossible
。
数据保证不存在负权回路。
输入格式
第一行包含整数 nn 和 mm。
接下来 mm 行每行包含三个整数 x,y,zx,y,z,表示存在一条从点 xx 到点 yy 的有向边,边长为 zz。
输出格式
输出一个整数,表示 11 号点到 nn 号点的最短距离。
如果路径不存在,则输出 impossible
。
题解:
将更新距离的点存入队列中 (只有被更新距离的点,才会更新其他点的距离)
再遍历与这点相连的边,查找是否存在可以被这个点更新距离的边了。
#include <cstring>
#include <iostream>
#include <algorithm>
#include<queue>
using namespace std;
const int N = 100010, M = 100010;
int n, m;
int dis[N];//当前每个点到1的最短距离
int h[N],w[N],e[N],ne[N],idx;//邻接表储存
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(dis,0x3f,sizeof dis);
dis[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(dis[j]>dis[t]+w[i])//判断距离是否被更新
{
dis[j]=dis[t]+w[i];
if(!st[j])
q.push(j);
{
st[j]=true;//记录这个点是否在队列中 如果已经在队列中则不需要再次加入
}
}
}
}
return dis[n];
}
int main()
{
scanf("%d%d", &n, &m);
memset(h,-1,sizeof h);
for (int i = 0; i < m; i ++ )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a,b,c);
}
int t=spfa();
if (t==0x3f3f3f3f) puts("impossible");
else printf("%d\n", t);
return 0;
}