PAT 1046. Shortest Distance

1046. Shortest Distance (20)

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 D1D2... DN, where Diis the distance between the i-th and the (i+1)-st exits, and DNis 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


思路:以dis[i]表示1号节点按顺时间方向到达“i号节点顺时钟方向的下一个节点”的距离*(1<<i<<N)于是对每个查询left---right,其结果就是dis(left, right)与sum - dis(left, right)中的最小值。

关键点

此题如果没有经过预处理dis数组(把dis数组做成一个累加数组)和sum的做法很容易超时

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 昨天偶然看到了无戒老师的365日更训练营挑战,毫不犹豫想要立马报个名。班长大人说,报名了就得更文,想想当时没有半点...
    大Ora小姐阅读 2,860评论 4 11
  • 今天开始学习本学期第四组课文,前言部分是这样的:有这样一本书—书中没有一个字,却处处都是学问;书上没有作者的姓名,...
    木木屋的故事阅读 3,772评论 0 1
  • 夏日炎炎,继“心理学系列”结束,开启“自我提升”与“优势计划”系列阅读。 6.24. 《枪炮、钢铁与病菌》(上) ...
    陌上花开wen阅读 5,087评论 0 3
  • 黄芦苦,黄芦苦,凄风冷雨霜儿树 飞光璞,飞光璞,赭衣帐前魂销骨 我自远方,手秉一盏干烛 来去草莽,进退几分尺度
    柠沐阅读 1,456评论 0 1
  • 这篇文章一如既往还是抄的。特意挑了一篇超简单的,里面命令都是最常用的,完全能解决日常使用。什么安装就不说了。谁让我...
    To_Be_Better阅读 884评论 0 0