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 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

 题目大意:给出一个圈,并且每个点之间的距离给出了;输出查询每对点之间的最短距离。

//感觉如果直接去查,肯定会超时的。。 想使用dp的思想,但写了一下状态转移公式,发现之前的并不能依次计算。感觉就是无厘头的循环啊。不太会这样的题目。

 //我的想法就是将from设置为小的那个,先计算from-to的最短距离,这个遍历一下就可以;再计算0-from+to-n的距离这样。

代码来自:https://www.liuchuo.net/archives/2021

#include <iostream>
#include <vector>
using namespace std;
int main() {
    int n;
    scanf("%d", &n);
    vector<int> dis(n + 1);
    int sum = 0, left, right, cnt;
    for(int i = 1; i <= n; i++) {
        int temp;
        scanf("%d", &temp);
        sum += temp;
        dis[i] = sum;
    }
    scanf("%d", &cnt);
    for(int i = 0; i < cnt; i++) {
        scanf("%d %d", &left, &right);
        if(left > right)
            swap(left, right);//可以直接使用swap函数。
        int temp = dis[right - 1] - dis[left - 1];
        printf("%d\n", min(temp, sum - temp));
    }
    return 0;
}

//这个代码简直是非常神奇了,我是想不出来。

1.首先sum存储的是环的总长度,

2.这个dis十分有趣了,对于样例有5个点来说:

dis[0]->0

dis[1]-> 1到2的距离,

dis[2]-> 1到3的距离,

dis[3]-> 1到4的距离,

dis[4]-> 1到5的距离,

dis[5]-> 1转一圈后到1的距离。

那么对于left到rigth来说,就是1到他们两者的距离相减,那么另一个距离因为是环,所以就是sum-这个距离。

//学习了!

猜你喜欢

转载自www.cnblogs.com/BlueBlueSea/p/9568100.html