【PAT甲级真题】- Shortest Distance (20)

题目来源

Shortest Distance - PTA
Shortest Distance - 牛客

Description

The task is really simple: given N N 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 N N ( in 3 , 10 5 3,10\^5 3,105 ), followed by N integer distances D 1 , D 2 ⋯ D N D_1,D_2\cdots D_N D1,D2⋯DN, where D i D_i Di is the distance between the i i i-th and the ( i + 1 ) (i+1) (i+1)-st exits, and D N D_N DN is between the N N 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 ) M(≤10^4) M(≤104), with M M M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 1 1 to N N N. It is guaranteed that the total round trip distance is no more than 10 7 10^7 107

.

Output Specification:

For each test case, print your results in M M 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

题目大意

一个有 N N N 个结点的环,给定每个相邻结点之间的距离、

输入若干组 a , b a,b a,b ,问结点 a , b a,b a,b 的最短距离

思路简介

前缀和

用前缀和数组 sum 维护距离, a → b a\to b a→b 的距离就是 s u m b − s u m a sumb-suma sumb−suma

len 表示环的总长度,则 b → a b\to a b→a 的距离就是 l e n − ( s u m b − s n u m a ) len-(sum\[b-snuma) len−(sum\[b−snum[a)

取最小值即可

遇到的问题

  1. 无,一遍过

代码

cpp 复制代码
/**
 * Shortest Distance
 * https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805435700199424
 * https://www.nowcoder.com/pat/5/problem/4085
 * 前缀和
 */
#include<bits/stdc++.h>
using namespace std;

const int N=1e5+10;
int d[N],n;

void init(){
    d[1]=0;
    cin>>n;
    for(int i=1;i<=n;++i){
        int tmp;cin>>tmp;
        d[i+1]=d[i]+tmp;
    }
}

void solve(){
    int i,j;
    cin>>i>>j;
    int len=d[n+1];
    int res=abs(d[j]-d[i]);
    cout<<min(res,len-res)<<'\n';
}   

int main(){
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    //fstream in("in.txt",ios::in);cin.rdbuf(in.rdbuf());
    int T=1;
    init();
    cin>>T;
    while(T--){
        solve();
    }
    return 0;
}
相关推荐
船厂电气自动化ai大模型10 小时前
AI大模型与数学·第57课 傅里叶全套工具链综合实战:串联级数/连续变换/DFT/FFT,图像、音频、扩散模型完整例题
数据结构·人工智能·深度学习·算法·机器学习
wuyk55510 小时前
从零吃透Modbus通信|第3章:STM32 Modbus RTU主机
服务器·开发语言·网络·数据结构·stm32·单片机·嵌入式硬件
人工智能培训11 小时前
人工智能数据安全下的个人信息保护实践方案
大数据·人工智能·算法·生活
Brilliantwxx11 小时前
【算法从零到千】【59-65】链表专题
数据结构·链表
元启数宇12 小时前
幕墙AI设计算法逻辑:元启数宇如何智能分格
人工智能·算法
宵时待雨12 小时前
优选算法专题16:多源BFS
算法·宽度优先
重生之后端学习12 小时前
53. 最大子数组和[中等]✅
java·数据结构·算法·leetcode·职场和发展
水饺编程12 小时前
第5章,[Win32 章节] :绘图模式
c语言·c++·windows·visual studio
INGNIGHT13 小时前
1908 · 布尔表达式求值(stack单调栈&dfs)
开发语言·c++·算法
lucas_AI13 小时前
把表格压成 64 个 token,长文档问答反而更准了:先找表,再看数
人工智能·深度学习·算法