当前位置: 首页 > news >正文

Shortest Routes II(Floyd最短路)

题目描述

There are n cities and m roads between them. Your task is to process q queries where you have to determine the length of the shortest route between two given cities.

输入

The first input line has three integers n, m and q: the number of cities, roads, and queries.
Then, there are m lines describing the roads. Each line has three integers a, b and c: there is a road between cities a and b whose length is c. All roads are two-way roads.
Finally, there are q lines describing the queries. Each line has two integers a and b: determine the length of the shortest route between cities a and b.
Constraints
1 ≤ n ≤ 500
1 ≤ m ≤ n2
1 ≤ q ≤ 105
1 ≤ a,b ≤ n
1 ≤ c ≤ 109

输出

Print the length of the shortest route for each query. If there is no route, print -1 instead.

样例输入

4 3 5
1 2 5
1 3 9
2 3 3
1 2
2 1
1 3
1 4
3 2

样例输出

5
5
8
-1
3

多源最短路问题,使用Floyd算法,要注意的是可能有重边,需要在输入时判断一下,去两个点之间最短的边

代码

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int N=510;
ll d[N][N];
int main() {ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int n,m,q;cin>>n>>m>>q;memset(d,0x3f,sizeof(d));for(int i=1;i<=n;i++)d[i][i]=0;for(int i=1;i<=m;i++){int a,b,c;cin>>a>>b>>c;d[a][b]=min(d[a][b],(ll)c);d[b][a]=min(d[b][a],(ll)c);}for (int k=1;k<=n;k++){for (int i=1;i<=n;i++){for (int j=1;j<=n;j++){d[i][j]=min(d[i][j],d[i][k]+d[k][j]);}}}while(q--){int a,b;cin>>a>>b;if (d[a][b]==0x3f3f3f3f3f3f3f3f)cout<<"-1\n";elsecout<<d[a][b]<<"\n";}
}

http://www.lryc.cn/news/622490.html

相关文章:

  • 数据结构:二叉树的表示方式(Representation of Binary Trees)
  • 【100页PPT】数字化转型集团信息化总体解决方案(附下载方式)
  • UI-TARS-Desktop 产品发展史:从实验室原型到企业级解决方案
  • gulimall项目笔记:P54三级分类拖拽功能实现
  • 深入理解C++正则表达式:从基础到实践
  • ramdisk内存虚拟盘(一)——前世今生
  • Python爬取推特(X)的各种数据
  • 功能组和功能组状态的概念关系和区别
  • 【揭秘红黑树:高效数据结构解析】
  • 谈谈《More Effective C++》的条款30:代理类
  • JavaScript 防抖(Debounce)与节流(Throttle)
  • Python入门第2课:变量、数据类型与输入输出
  • MySQL(多表查询练习)
  • C#控制台输入(Read()、ReadKey()和ReadLine())
  • 【大模型微调系列-01】 入门与环境准备
  • Linux信号保存
  • PowerShell 格式化系统完全掌握(上):工作原理、默认规则与三大格式化命令
  • 【数据分享】上市公司创新韧性数据(2007-2023)
  • 数据处理分析环境搭建+Numpy使用教程
  • MySQL、PolarDB、PolarDB-X、TableStore、MongoDB、TiDB、ClickHouse选型
  • CIAIE 2025上海汽车内外饰展观察:从美学到功能的产业跃迁
  • 中级统计师-会计学基础知识-第一章 账户与复试记账
  • imx6ull-驱动开发篇25——Linux 中断上半部/下半部
  • 嵌入式学习 day52 IMX6ULL裸机开发-I2C
  • Redis核心应用场景及代码案例
  • WordPress 7B2主题,在使用PHP 8.0+出现502的解决办法。
  • 【机器学习深度学习】OpenCompass 评测指标全解析:让大模型评估更科学
  • platform总线注册流程分析
  • 洛谷 P2842 纸币问题 1 -普及-
  • C++类与对象核心知识点全解析(下)