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

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.xdnf.cn/news/17825.html

相关文章:

  • 数据结构初阶(15)排序算法—交换排序(快速排序)(动图演示)
  • Docker 缓存优化:通过 cpolar 内网穿透服务远程管理 Redis
  • C语言零基础第17讲:数据在内存中的存储
  • 新手向:Python函数定义与参数传递(位置参数、关键字参数、默认参数)
  • Redis 实用型限流与延时队列:从 Lua 固定/滑动窗口到 Streams 消费组(含脚本与压测)
  • 眺望电子RK3588_SDIO_WiFi_Support List更新
  • nodejs03-常用模块
  • LeetCode 53.最大子数组和:贪心算法下的连续子数组最优解
  • 【测试用例】
  • STM32 - Embedded IDE - GCC - 解决LWRB库在GCC编译器会编译失败,在ARMCC编译器时却正常编译
  • 肖臻《区块链技术与应用》第16讲 - 以太坊的“世界状态”:从哈希表到MPT架构演进
  • 安装openmmlab时出错
  • IStoreOS(OpenWrt)开启IPV6
  • LeetCode 刷题【42. 接雨水】
  • 大规模Go网络应用的部署与监控实战指南
  • python30-正则表达式
  • 应急救援智能接处警系统——科技赋能应急,筑牢安全防线
  • 线程P5 | 单例模式[线程安全版]~懒汉 + 饿汉
  • 从0开始学习Java+AI知识点总结-15.后端web基础(Maven基础)
  • UI-TARS-Desktop 产品发展史:从实验室原型到企业级解决方案
  • 流处理、实时分析与RAG驱动的Python ETL框架:构建智能数据管道(中)
  • python中的map函数
  • Android UI(一)登录注册 - Compose
  • 【数据可视化-89】基孔肯雅热病例数据分析与可视化:Python + pyecharts洞察疫情动态
  • RH134 管理基本存储知识点
  • 【C#补全计划】泛型约束
  • OpenCv(二)——边界填充、阈值处理
  • 37 C++ STL模板库6-string_view
  • Mybatis实现页面增删改查
  • 解锁AI潜能:五步写出让大模型神级指令