题目描述
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
分析
测试点三超时思路:刚开始想的是将编数据存放到数组中,下标就作为顶点,查找的过程中就可以直接累加start-end的数组数据就可以了,中途也是要判断start和end数字的大小,还有就是输出的是哪一个圈圈,刚开始是手写比大小和交换数字大小,后来才明白其实是可以用swap和min函数的。超时原因就是外面一层循环控制输入数据的组数,内层还有一个遍历数组的for循环。
改进
改进就是时用一个叫做dis的数组进行存储第一个顶点到第i+1个顶点的距离,这个具体描述参考算法详解具体介绍,我觉得这个的好处就是,可以省略掉遍历数组的操作,dis数组中直接存储的是距离,之后直接使用dis[right-1]-dis[left-1]就可以了,通俗一点的理解就是可以将她想象成一段线段,要求的就是中间的一段长度,就是用当前位置的总长度-截取线段长度的开始数值就可以了。
超时代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int a[100000];
int n,m,start,end;
int sum=0,ans1=0,asn2=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
scanf("%d",&m);
for(int i=0;i<m;i++)
{
ans1=0;
scanf("%d %d",&start,&end);
if(start>end)
{
int temp;
temp=start;
start=end;
end=temp;
}
for(int j=start;j<end;j++)
{
ans1+=a[j];
}
if(ans1<sum-ans1)
{
printf("%d",ans1);
}else {
printf("%d",sum-ans1);
}
if(i<m-1)
{
printf("\n");
}
}
return 0;
}
正确代码
#include<bits/stdc++.h>
using namespace std;
const int MAXN=100005;
int dis[MAXN],A[MAXN]={0};
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int sum=0;
int query,n,left,right;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&A[i]);
sum+=A[i];
dis[i]=sum;
}
scanf("%d",&query);
for(int i=0;i<query;i++)
{
scanf("%d %d",&left,&right);
if(left>right)
{
swap(left,right);
}
int temp=dis[right-1]-dis[left-1];
printf("%d\n",min(temp,sum-temp));
}
return 0;
}
总结
求最小值和交换数值时可以直接使用swap函数和min函数的,还有就是一种新的方法,求一段长度的时候,如果超时,就可以使用一个新的数组,记录每一个小终点到初始点的距离,这样子就可以解决超时问题。