本文主要是介绍Codeup ContestID:100000575 问题 E: Shortest Distance (20),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:http://codeup.cn/problem.php?cid=100000575&pid=4
题目描述
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.
输入
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 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 (<=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.
输出
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
代码
#include<stdio.h>int main() {int a[100010], sum = 0, n, i, j; //数组长度小的话,提交显示运行错误!!!while(scanf("%d", &n) != EOF) { for(i = 1; i <= n; i++){scanf("%d",&a[i]);sum += a[i];}int s , m, l1, l2;scanf("%d", &m);for(j = 0; j < m; j++){s = 0;scanf("%d%d",&l1, &l2);while(l1 != l2) {s += a[l1];l1 = l1 >= n ? (l1 + 1) % n : l1 + 1 ; //此循环数组不是从零开始,要特殊处理l1为n的元素。(以防出错,循环数组尽量从0开始)}printf("%d\n", s < sum - s ? s: sum - s); //三元运算符}}return 0;}
这篇关于Codeup ContestID:100000575 问题 E: Shortest Distance (20)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!