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
相关推荐
闻缺陷则喜何志丹5 分钟前
【动态规划】数位DP的原理、模板(封装类)
c++·算法·动态规划·原理·模板·数位dp
豆沙沙包?22 分钟前
2025年--Lc194-516. 最长回文子序列(动态规划在字符串的应用,需要二刷)--Java版
java·算法·动态规划
胖咕噜的稞达鸭23 分钟前
二叉树搜索树插入,查找,删除,Key/Value二叉搜索树场景应用+源码实现
c语言·数据结构·c++·算法·gitee
showmethetime23 分钟前
基于相空间重构的混沌时间序列预测MATLAB实现
算法
进击的大海贼42 分钟前
QT-C++ 自定义加工统计通用模块
开发语言·c++·qt
地平线开发者1 小时前
大模型 | VLM 初识及在自动驾驶场景中的应用
算法·自动驾驶
lingran__1 小时前
算法沉淀第四天(Winner)
c++·算法
AIzealot无1 小时前
Qwen3 Embedding报告随笔
人工智能·深度学习·算法·论文·embedding·论文笔记·搜广推
zzzsde1 小时前
【C++】深入理解string类(5)
java·前端·算法
清风wxy1 小时前
C语言基础数组作业(冒泡算法)
c语言·开发语言·数据结构·c++·windows·算法