【PAT甲级 - C++题解】1046 Shortest Distance
创始人
2024-05-07 02:13:16
0

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1046 Shortest Distance (pintia.cn)
🔑中文翻译:最短距离
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

1046 Shortest Distance

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.

Input Specification:

Each input file contains one test case. For each case, the first line contains an integer N (in [3,105]), followed by N integer distances D1 D2 ⋯ DN, where Di is the distance between the i-th and the (i+1)-st exits, and DN is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (≤104), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 107.

Output Specification:

For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.

Sample Input:

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

Sample Output:

3
10
7

题意

在一个环形的公路上有 n 个出口,现在给定一个序列 {D1 D2 ⋯ DN} ,其中 Di 表示第 i 个出口与第 i+1 个出口之间的距离, Dn 表示第 n 个出口与第 i 个出口之间的距离。

现在给定 m 个询问,需要我们输出给定两个出口之间的距离。

思路

这道题可以用前缀和的方法来做,创建一个数组 s 记录距离总和,其中 s[i] 表示第 1 个出口到第 i+1 个出口的距离之和。

这样一来,我们就可以通过 s[r-1]-s[l-1] 来计算出第 r 个出口与第 l 个出口之间的距离了。

但是,需要注意的是这是一个环形公路,所以还要计算 r...1...l 这段路径,然后与上面计算的路径作比较取最小值输出。而这段路径可以先计算出第 r 个路口到第 1 个路口的距离,即 s[n]-s[r-1] 。然后再计算第 1 个路口的距离到第 l 个路口的距离,即 s[l-1] 。两者相加就是这段距离之和,即 s[n]-s[r-1]+s[l-1]

故最终的答案就使求上面两个路径的最小值并输出,即 min(s[r-1]-s[l-1],s[n]-s[r-1]+s[l-1])

代码

#include
using namespace std;const int N = 100010;
int s[N];
int n, m;int main()
{//输入数组元素并求前缀和scanf("%d", &n);for (int i = 1; i <= n; i++){scanf("%d", &s[i]);s[i] += s[i - 1];}//进行询问scanf("%d", &m);while (m--){int l, r;scanf("%d%d", &l, &r);if (l > r) swap(l, r);printf("%d\n", min(s[r - 1] - s[l - 1], s[n] - s[r - 1] + s[l - 1]));}return 0;
}

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...