【PAT A1046】 Shortest Distance
发布日期:2021-06-29 11:18:08
浏览次数:2
分类:技术文章
本文共 1880 字,大约阅读时间需要 6 分钟。
The task is really simple: given N N 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 N N (in [3, 1 0 5 10^5 105]), followed by N N N integer distances D 1 D 2 ⋯ D N D_1D_2⋯D_N D1D2⋯DN, where D i D_i Di is the distance between the i i i-th and the ( i i i+1)-st exits, and DN is between the N N 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 M M (≤ 1 0 4 10^4 104), with M M M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N N N. It is guaranteed that the total round trip distance is no more than 1 0 7 10^7 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 931 32 54 1
Sample Output:
3107
思路:路径为环形,可以顺时针也可以逆时针,两种路径长度之和为环周长,故第二种路径长度=总长度-第一种路径长度,且两者最小值为最短路径。所以我们只需求固定的一种路径就行(这里求的是标号从小到大的路径)。如果直接是把两点之间的长度放入数组,然后再累计求和,遇到数据比较多的情况下会超时。这里采用的方法是前缀和。即读入数据时同时用一个数组记录从1号点到其他所有点的距离,可以降低算法复杂度
#include#include using namespace std;int a[100000], d[100000];//全局变量数组声明时默认元素全为0int main() { int n; while (scanf("%d", &n) != EOF) { //codeup上是多点测试 int sum = 0; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); sum += a[i]; d[i + 1] = sum;//记录从第一个点到第i+1个点之间的距离 } int m; scanf("%d", &m); while (m--) { int x, y; scanf("%d%d", &x, &y); if (x > y) { swap(x, y); } int dis = d[y] - d[x];// printf("%d\n", min(dis, sum - dis)); } } return 0;}
转载地址:https://blog.csdn.net/zxc0074869/article/details/115247673 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2024年04月26日 08时45分31秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
突破!台积电1nm芯片,有了新进展。
2019-04-29
一文读懂全系列树莓派!
2019-04-29
自制一个害羞的口罩,见人就闭嘴,戴着可以喝奶茶
2019-04-29
聊聊我是如何编程入门的
2019-04-29
J-Link该如何升级固件?
2019-04-29
从电子垃圾中提炼黄金,可以!!!
2019-04-29
知乎大神深入解析:单片机晶振脚原理是什么?
2019-04-29
电容有17种?看看详细介绍!
2019-04-29
如何准备电赛?19年电赛经验总结!
2019-04-29
蓝牙:为啥叫“蓝”牙,不叫“白”牙?
2019-04-29
干货 | 如何系统学习 C 语言?
2019-04-29
多层PCB内部长啥样? 3D大图解析高端PCB板的设计工艺
2019-04-29
鸿蒙2.0都来了,快搭个环境玩起来吧!
2019-04-29
PCB散热的10种方法!
2019-04-29
值得收藏!268条PCB layout设计规范
2019-04-29
Keil升级了,Keil Studio 来了!
2019-04-29
关于RS-485总线,这篇很详细
2019-04-29
关于2021年电赛的一些想法,看到就是赚到!
2019-04-29
教你一秒分辨真假芯片!
2019-04-29
抽奖 | 送STM32开发板
2019-04-29