AcWing 851. spfa求最短路
原题链接
简单
作者:
20岁带专生陈刀仔
,
2021-04-22 16:27:31
,
所有人可见
,
阅读 303
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#define N 100010
#define INF 0x3f3f3f3f
int n, m;
int dist[N];
int queue[N];
bool inQue[N];
int head, tail;
int h[N], cnt;
struct edge{
int to;
int next;
int weight;
}E[N];
void add(int v, int w, int weight){
E[++cnt].next = h[v];
E[cnt].to = w;
E[cnt].weight = weight;
h[v] = cnt;
}
int spfa(){
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
queue[++tail] = 1; inQue[1] = true;
while(head != tail){
int t = queue[++head];
inQue[t] = false;
for(int i = h[t]; i != -1; i = E[i].next){
int u = E[i].to;
if(dist[t] + E[i].weight < dist[u]){
dist[u] = dist[t] + E[i].weight;
if(!inQue[u]){
queue[++tail] = u;
inQue[u] = true;
}
}
}
}
if(dist[n] == INF) return -1;
else return dist[n];
}
int main(){
scanf("%d %d", &n, &m);
memset(h, -1, sizeof h);
for(int i = 1; i <= m; i++){
int a, b, w;
scanf("%d %d %d", &a, &b, &w);
add(a, b, w);
}
int res = spfa();
if(res == -1) printf("impossible");
else printf("%d", res);
return 0;
}