当前位置: 首页 > 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.dtcms.com/a/333023.html

相关文章:

  • 管家婆辉煌系列试用版/期限说明
  • Shader开发(十三)理解片元插值
  • 淘米自动签到脚本
  • 大气负氧离子自动监测站:解密空气的科技密码
  • 有红帽认证证书可以0元置换华为openEuler-HCIA/HCIP认证
  • OpenSCA开源社区每日安全漏洞及投毒情报资讯|13th Aug. , 2025
  • MyBatis StatementHandler核心原理详解
  • Nginx反向代理Tomcat实战指南
  • mysql-DDLy语句案例
  • 基于asp.net#C##VUE框架的独居老人物资配送系统的设计与实现#sql server#visual studio
  • OpenZeppelin Contracts 架构分层分析
  • 基于机器学习的赌博网站识别系统设计与实现
  • 【计算机视觉与深度学习实战】02基于形态学的权重自适应图像去噪系统
  • 【车联网kafka】常用参数及其命令总结(第八篇)
  • 【展厅多媒体】数字展厅小知识:实物识别桌是什么?
  • 杂记 02
  • Java研学-SpringCloud(四)
  • YOLO12 改进、魔改|幅度感知线性注意力MALA,提升小目标、遮挡的检测能力
  • FDBus CBaseWork运行在当前线程
  • AKShare开源金融数据接口库 | 1、介绍
  • 驱动-总线bus注册流程分析
  • QT开发中QString如何截取字符串
  • 怎样使用数据度量测试
  • Leetcode SQL基础50题
  • 旋钮键盘项目---foc讲解(开环)
  • 转换一个python项目到moonbit,碰到报错输出:编译器对workflow.mbt文件中的类方法要求不一致的类型注解,导致无法正常编译
  • 如何将堡塔云WAF迁移到新的服务器
  • 高精度标准钢卷尺优质厂家、选购建议
  • leetcode 342. 4的幂 简单
  • Flink Stream API 源码走读 - keyBy