博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[A] 1046 Shortest Distance
阅读量:6716 次
发布时间:2019-06-25

本文共 1802 字,大约阅读时间需要 6 分钟。

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


晚上被这道题坑了很久,一直没想明白为什么不能完全ac,会出现超时,只能拿17/20的分,,我一开始的想法是每次都一个循环遍历相加来求距离,查了网上资料说,在极端情况下,每次查询都需要遍历整个数组,即有1e5次操作,而共有1e4次查询,所以极端情况下会有1e9次操作,这在100ms内往往会超时。

解决办法是一开始设置一个dis[i]表示1号结点顺时针方向到达i号结点的下一个结点的距离,这样在输入时就可以直接得到dis,因此查询复杂度可以直接达到o(1),这样就好了orz.。。

#include
using namespace std;#define MAX 100001int dis[MAX] , a[MAX];int main(void){ int sum = 0; int n,m,v1,v2; scanf("%d",&n); for(int i = 1; i <= n; i++){ scanf("%d",&a[i]); sum += a[i]; dis[i] = sum; } scanf("%d",&m); while(m--){ scanf("%d %d",&v1,&v2); if(v1 > v2){ int t = v1; v1 = v2; v2 =t; } int ans = dis[v2-1] - dis[v1-1]; if(ans > (sum-ans) ) ans = sum -ans; printf("%d\n",ans); } return 0;}

转载于:https://www.cnblogs.com/hish/p/10247460.html

你可能感兴趣的文章
关于CCR测评器的自定义校验器(Special Judge)
查看>>
java设计模式之 装饰器模式
查看>>
利息力(force of interest)
查看>>
Oracle 角色及其权限
查看>>
NiftyDialogEffects:集成了多种动画效果的Dialog控件
查看>>
《世界是数字的》读后感
查看>>
AD软件原理图封装过程(即由原理图转换到PCB)
查看>>
cocos2d-x lua table与json的转换
查看>>
mysql的基本原理
查看>>
《面向对象分析与设计》——抽象
查看>>
linux学习记录-------jdk安装配置
查看>>
查看dll依赖项
查看>>
ansible普通用户su切换问题
查看>>
2017.10.1
查看>>
洛谷——P1187 3D模型
查看>>
温度传感器,ds18b20
查看>>
ecshop为什么删不掉商品分类
查看>>
bzoj1941[Sdoi2010]Hide and Seek
查看>>
IT兄弟连 Java Web教程 经典面试题2
查看>>
利用setTimeoutc处理javascript ajax请求超时
查看>>