1046. Shortest Distance (20)
来源:互联网 发布:非结构化数据存储方案 编辑:程序博客网 时间:2024/06/08 11:40
1046. Shortest Distance (20)
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 931 32 54 1Sample Output:
3107
提交代码
题目大意:
有构成环的n个点,给定每个点之间的距离,然后给出m组查询,查询给出的两个点之间的最短距离。
解题思路:
不管查询哪个点都以第一个点为起始点,用一个数组记录每个点到第一个点的距离,然后要查询的两个点减去相同的距离,就是他们之间的距离。查询的时候
需要注意判断是左边的大还是右边的大,用这种方法一定是大的减去小的。但是因为成环,所以有两条不同的方向可以到达,所以我们要取两者的最小值,那
么我们就可以直接把这个环的总长度记录下来,用总长度减去一个方向的就可以得到另一个方向的了。相减的时候需要注意,是dis[r-1]-dis[l-1]。自己
画个图就很容易理解。
#include<iostream>#include<cstdio>#include<algorithm>using namespace std;#define N 100005int dis[N];int main(){//freopen("input.txt","r",stdin);int sum = 0;int l,r,ncase,n,num;scanf("%d",&n);for(int i = 1;i <= n;i++){scanf("%d",&num);sum += num;dis[i] = sum;}scanf("%d",&ncase);while(ncase--){scanf("%d%d",&l,&r);if(l>r){swap(l,r);}int temp = dis[r-1]-dis[l-1];printf("%d\n",min(temp,sum-temp));}}
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- FPGA作业1:利用74138设计4-16译码器
- python3.5 Unable to find vcvarsall.bat
- 如何修改maven默认jdk配置
- [题解] 八数码问题 (哈希表+搜索)
- 关于NGUI与UGUI的区别
- 1046. Shortest Distance (20)
- 第七次作业
- 深度学习初学篇一
- 判断输入的三角形边长能否构成三角形
- HDU2674 N!Again 解题报告【阶乘】
- 计蒜客————跳跃游戏二
- 3、JACK Audio Connect Kit低延迟音频服务——Qjackctl基本设置
- 20171018
- HDU3572(最大流)