A1046. Shortest Distance
题目描述
The task is really simple: given N exits on a high way which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits
输入格式
Each input file contains on test case. For each case, the first line contains an integer N (in[3, 105]), followed by N integer distances D1 D2 ... DN , where D1 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 exists are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 107
输出格式
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
输入样例
5 1 2 4 14 9
3
1 3
2 5
4 1
输出样例
3
10
7
题意
N个结点围成一个圈,相邻两个点之间的距离已知,且每次只能移动到相邻点。然后给出M个询问,每个询问给出两个数字A和B,即结点编号(1≤A,B≤N),求从A
号结点到B号结点最短距离
输入格式
每个输入文件包含一个测试用例
对于每种情况,第一行都包含一个整数N(在[3,105]中),后跟n个整数距离D1 D2 ... DN,其中D1是第i个与(i + 1)之间的距离出口,而DN在第N个出口和第一个出口之间。
一行中的所有数字都用空格分隔。 第二行给出一个正整数M(≤104),紧随其后的M行,每行包含一对出口号,条件是出口的编号从1到N。确保本地往返距离不超过 107
输入样例,有3个查询,分别是1,3;2,5;4,1
解题思路
- 这是一个圆,圆上两端点间距离的最小值,就是两点间的劣弧
const int MAXN = 100000; int dis[MAXN], A[MAXN];// dis 数组含义已说明,A[i] 存放i号与i+1 号顶点的距离 int main(int argc, char *argv[]) { int sum = 0, query, n, left, right; scanf("%d", &n); for(int i = 1; i <= n; i++){ scanf("%d", &A[i]); sum += A[i]; dis[i] = sum;// 初始化dis数组 } scanf("%d", &query); for(int i = 0; i < query; i++){ scanf("%d%d", &left, &right); if(left > right){ swap(left, right); } int temp = dis[right - 1] - dis[left - 1];// 两端点沿顺时针的方向的弧 printf("%d\n", min(temp, sum - temp));// 选择劣弧输出 } return 0; }
睁开眼,书在面前 闭上眼,书在心里