当前位置:网站首页>第三讲:spfa求最短路
第三讲:spfa求最短路
2022-07-15 18:07:00 【奋斗吧!骚年!】
题目:AcWing 851. spfa求最短路
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 impossible。
数据保证不存在负权回路。
输入格式
第一行包含整数 n 和 m。
接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。
输出格式
输出一个整数,表示 1 号点到 n 号点的最短距离。
如果路径不存在,则输出 impossible。
数据范围
1≤n,m≤105,
图中涉及边长绝对值均不超过 10000。
输入样例:
3 3
1 2 5
2 3 -3
1 3 4
输出样例:
2
#include <iostream>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
using namespace std;
typedef pair<int,int> PII;
map<int,vector<PII>> list;
const int N = 100010;
int n,m;
int dist[N],st[N];
void 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(auto it:list[t])
{
if(dist[it.first]>dist[t]+it.second)
{
dist[it.first]=dist[t]+it.second;
if(!st[it.first])
{
q.push(it.first);
st[it.first]=true;
}
}
}
}
}
int main()
{
cin>>n>>m;
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
list[a].push_back({
b,c});
}
spfa();
if(dist[n]==0x3f3f3f3f)cout<<"impossible"<<endl;
else cout<<dist[n]<<endl;
return 0;
}
边栏推荐
- Log in and operate the database with the command line
- Software architecture and design (I) -- key principles
- Li Mu hands on deep learning V2 target detection SSD
- Anhui University landmark
- ncnn 推理框架安装;onnx转ncnn
- 阿里最新总结2022年大厂面试真题+核心知识点全面覆盖+答案详解
- The space dream of billionaires is killing the earth
- YesDev:轻松协作每一个项目
- 307. Area and retrieval - array modifiable
- 短视频商城系统,系统提示框、确认框、点击空白关闭弹出框
猜你喜欢

Blue whale configuration framework

(zero six) flask is OK if you have hands - configure static files

Anhui University store

LDAP introduction

The space dream of billionaires is killing the earth

Matlab: build neural network

GeoServer complete tutorial

Meituan side: why does thread crash not cause JVM crash?

Pytoch distributed training

Face beating
随机推荐
EasyCVR视频调阅页面如何增加对应视频的云台控制?
Consumer start flash back
Matlab: build neural network
Create and generate WiFi QR code mobile phone scanning link
#夏日挑战赛# HarmonyOS 实现一个手绘板
Is it safe to open an account online now? Want to know which are the top ten securities dealers in China?
The space dream of billionaires is killing the earth
One question per day · 873 The length of the longest Fibonacci subsequence Mnemonic search
傅立叶变换的物理意义
傅立葉變換的物理意義
Broadcast mechanism in pytoch
Openpyxl drawing pie chart
Lifecycle: the foundation of lifecycle aware components - jetpack series (1)
The physical meaning of Fourier transform
Daily question · 1217 Playing chips · greed
Software architecture and design (VIII) -- distributed architecture
8254 timer / counter application experiment
How to set the allure test report
Basic knowledge of capacitance
Daily question 1: the minimum value of the sum of the largest number pairs in the array (leecode)