1046 Shortest Distance (PAT甲级)

cpp 复制代码
#include <cstdio>
#include <vector>
#include <algorithm>

int N, M, d, u, v, sum, tmp;
std::vector<int> dist;

int main(){
    scanf("%d", &N);
    sum = 0;
    dist.push_back(0);
    for(int i = 0; i < N; ++i){
        scanf("%d", &d);
        sum += d;
        dist.push_back(sum);
    }
    scanf("%d", &M);
    for(int i = 0; i < M; ++i){
        scanf("%d %d", &u, &v);
        if(u > v){
            std::swap(u, v);
        }
        tmp = dist[v - 1] - dist[u - 1];
        if(tmp * 2 > sum){
            tmp = sum - tmp;
        }
        printf("%d\n", tmp);
    }
    return 0;
}

题目如下:

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
相关推荐
数研小生4 小时前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克4 小时前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
Python 老手4 小时前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.4 小时前
优选算法【专题九:哈希表】
算法·哈希算法·散列表
Bella的成长园地5 小时前
面试中关于 c++ async 的高频面试问题有哪些?
c++·面试
爱看科技5 小时前
微美全息(NASDAQ:WIMI)研究拜占庭容错联邦学习算法,数据安全与隐私保护的双重保障
算法
彷徨而立5 小时前
【C/C++】什么是 运行时库?运行时库 /MT 和 /MD 的区别?
c语言·c++
qq_417129255 小时前
C++中的桥接模式变体
开发语言·c++·算法
YuTaoShao6 小时前
【LeetCode 每日一题】3010. 将数组分成最小总代价的子数组 I——(解法二)排序
算法·leetcode·排序算法
吴维炜7 小时前
「Python算法」计费引擎系统SKILL.md
python·算法·agent·skill.md·vb coding