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 ⋯ 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 (≤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数组定义为从点1到点i的下一个节点的距离,这里定义为点i的下一个节点而不是到点i的距离,原因是如果那样表示的话,就无法表示从点N到点1了(中间没有点0),因此这样定义方便一些。另一种结局思路就是加上一个“点0“,点0到点1距离为0也可。如果要求点i到点j的距离,那么就是dis[j-1]-dis[i-1]
。那么另一个方向的走法要怎么计算呢?因为题中给出的是一个环,即距离总长度是不变的,所以我们只需要用总长度减去这个距离,就是从另一个方向走需要的距离了(这两个点将圆分成了两半)。
代码
//
// Created by masterCai on 2020/5/15.
//
#include <iostream>
#include <vector>
using namespace std;
int main(){
int N;
cin >> N;
vector<int> dis(N+1);
int sum = 0;
int left, right;
for (int i = 1; i <= N; ++i) {
int tmp;
scanf("%d", &tmp);
sum += tmp;
dis[i] = sum;
}
int M;
cin >> M;
for (int i = 0; i < M; ++i) {
scanf("%d %d", &left, &right);
if(left > right){
swap(left, right);
}
int tmp = dis[right-1] - dis[left-1];
printf("%d\n", min(tmp, sum-tmp));
}
return 0;
}