PAT 1046 Shortest Distance python解法

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,10​5​​ ]), followed by N integer distances D​1​​ D​2​​ ⋯ D​N​​ , where D​i​​ is the distance between the i-th and the (i+1)-st exits, and D​​N​​ 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 (≤10​4​​ ), 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 10​7​​ .

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个数,组成一个圆环,知道每个点之间的距离,求两个点之间的最短距离。

解题思路:首先是用传统方法做了一遍,把顺时针和逆时针的距离都算出来进行比较,输出小的结果,这会导致2号测试点超时。随后发现,因为这是一个圆环,所以逆时针的距离其实就是圆环总距离减去顺时针的距离,也就是说从3到1的距离可以看做总距离减去顺时针从1到3的距离。而顺时针的距离可以直接先算出来存到一个列表中。

l = list(map(int,input().split()))
n = int(input())
#l = [5, 1, 2, 4, 14, 9]
#n = 3
dis = l.copy()
dis[0] = 0
summ = 0
for i in range(1,l[0]+1):
    summ += l[i] 
    dis[i] = summ
#print(summ,dis)
for i in range(n):
    d1, d2 = map(int,input().split())
    if d2 > d1:
        total = dis[d2-1] - dis[d1-1]
    else:
        total = dis[d1-1] - dis[d2-1]
    if total < summ - total:
        print(total)
    else:
        print(summ - total)

猜你喜欢

转载自blog.csdn.net/qq_36936510/article/details/86558547