ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

PAT (Advanced Level) Practice 1046 Shortest Distance (20 分) 凌宸1642

2021-04-05 02:33:45  阅读:205  来源: 互联网

标签:Distance contains PAT 1046 exits between 距离 出口 each


PAT (Advanced Level) Practice 1046 Shortest Distance (20 分) 凌宸1642

题目描述:

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.

译:你的任务很简单:给定 N 个出口,形成一个简单的圆形公路,你应该说出任意一对出口之间的最短距离。


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.

译:每个输入文件包含一个测试用例,每个用例在第一行中包含一个正整数 N ( 3 ≤ N ≤10 5 ) , 紧跟着 N 个表示距离的整数 D1 D2 ⋯ DN , Di 表示 第 i 个 出口到第 i + 1 个出口之间的距离, DN 表示第 N 个出口到第 1 个出口之间的距离。所有的数字被一个空格分隔。第二行给出一个正整数 M (≤104) , 接下来 M 行,每行包含一对出口的编号,保证出口在 1 ,N之间。题目保证整个环道的距离不超过 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.

译:对于每个测试用例,在 M 行中打印相应那对出口之间的最短距离 。


Sample Input (样例输入):

5 1 2 4 14 9
3
1 3
2 5
4 1

Sample Output (样例输出):

3
10
7

The Idea:

本题的最短距离还算简单。我们只需要一个 数组存储 第 1 个出口 到 第 i 个出口之间的距离。然后求两个出口之间的距离,就变成了简单的减法问题,由于是一个环道,最短距离需要考虑在两个距离之间抉择:a 到 b 的距离 和整个环道的距离 减去 a 到 b 的距离 。


The Codes:

#include<bits/stdc++.h>
using namespace std ;
#define MAX 100010
int sum[MAX] = { 0 } ; 
int n , m , t , a , b ;
int main(){
	scanf("%d" , &n) ;
	for(int i = 1 ; i <= n ; i ++){
		scanf("%d" , &t) ;
		sum[i] = sum[i-1] + t ; // 计算 第 1 个出口 到 第 i 个出口之间的距离。
	}
	scanf("%d" , &m) ;
	while(m --){
		scanf("%d%d" , &a , &b) ;
		if(a > b) swap(a , b) ; // 如果 a 大于 b 就交换一下
		cout<<min(sum[b - 1] - sum[a - 1] , sum[n] - (sum[b - 1] - sum[a - 1]))<<endl ;
	}
	return 0;
}

标签:Distance,contains,PAT,1046,exits,between,距离,出口,each
来源: https://www.cnblogs.com/lingchen1642/p/14617680.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有