时间限制:100ms
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
=============================================
此题原以为很简单,刚想疑问为啥PAT上正确率就0.2几….自己做了才发现原来会超时,因为数据量很大。
最初的想法超级简单,就是记录下每个顶点间的距离,等到有查询的时候再一个个计算~结果尼玛第三个测试点妥妥的超时了!
肯定是算法有问题,因为算法实在太简单了。
后来嘛,后来去网上一搜,搜了一半想到两个问题:
1.整个圆圈的总长度知道了,我算出一边,那么另一边的长度一减就出来了
2.从点x到点y(假设x小于y)的长度,不就是从 1到y的长度减去从1到x的长度(1点为第一个点)
而从1到i的长度,其实在读入数据的时候不就可以计算了!!!!!
dist_sum[i] = dist[i-1] + currDist;
之所以这两种做法时间上差别那么多,
因为幼稚的方法里面,每次计算时间复杂度是O(n),一共M次查询就是O(M*n)
现在每次查询时间复杂度是O(1),M次查询也就O(M)
题目给的规模,n=100000, M=10000
差距可想而知~
=================================
#include
int getShortestDist(const int* dists, int N, int from, int to, long totalDist)
{
int dist_L, dist_R;
if(from > to)
{
int temp = from;
from = to;
to = temp;
}
dist_L = dists[to-1] - dists[from-1];
dist_R = totalDist - dist_L;
return (dist_L
测试点 结果 用时(ms) 内存(kB) 得分/满分 0 答案正确 0 780 14/14 1 答案正确 0 790 3/3 2 答案正确 10 1000 3/3