A1046 Shortest Distance
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,10^5 ]), followed by N integer distances D1D2⋯ DN , where Diis the distance between the i-th and the (i+1)-st exits, and DNis 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 (≤10^4 ), 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 10^7.
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
题目为基础题型,只需严格按照题目要求输入输出即可
首次代码
#include<cstdio>
int main(){
int n,m,sum=0,x,y,z;
int a[n],b[n];
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
sum+=a[i];
}
scanf("%d",&m);
for(int i=0;i<m;i++){
int c=0,d;
scanf("%d %d",&x,&y);
if(x>y){
int temp=x;
x=y;
y=temp;
}
for(int j=x;j<y;j++){
c+=a[j-1];
}
d=sum-c;
if(c>d)
b[i]=d;
else if(c<d)
b[i]=c;
}
int i=0;
for(i=0;i<m-1;i++)
printf("%d\n",b[i]);
printf("%d",b[i]);
}
首次写完运行后发现没问题,提交后提示段错误
一脸懵…
关于段错误
段错误的产生一般是因为访问的内存超出了系统所给这个程序的内存空间
一般有两种情况:
1、访问数组时超过数组边界
2、数组的长度是负值
再次审题后发现忽略了对N和M的限制,导致使用较大数据测试时超出数组边界
修改如下:
#include<cstdio>
const int MAXN=100005;
int a[MAXN];
int main(){
int n,m,sum=0,x,y,z;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
sum+=a[i];
}
scanf("%d",&m);
int b[m];
for(int i=0;i<m;i++){
int c=0,d;
scanf("%d %d",&x,&y);
if(x>y){
int temp=x;
x=y;
y=temp;
}
for(int j=x;j<y;j++){
c+=a[j-1];
}
d=sum-c;
if(c>d)
b[i]=d;
else if(c<d)
b[i]=c;
}
int i=0;
for(i=0;i<m-1;i++)
printf("%d\n",b[i]);
printf("%d",b[i]);
}
定义常量MAXN后预处理a数组
此时段错误消失,出现运行超时错误
关于运行超时
代码时限为200ms
这就要求尽可能缩短代码查询时间复杂度
当前代码时间复杂度大于O(1),在极端情况下会查询10^9次,过大
改进方法:
去除循环嵌套,只用单层循环,保证时间复杂度为O(n)
如下:
#include<cstdio>
const int MAXN=100005;
int a[MAXN],b[MAXN];
int main(){
int n,m,sum=0,x,y,z;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
sum+=a[i];
b[i]=sum;
}
scanf("%d",&m);
int f[m];
for(int i=0;i<m;i++){
int c,d;
scanf("%d %d",&x,&y);
if(x>y){
int temp=x;
x=y;
y=temp;
}
c=b[y-1]-b[x-1];
d=sum-c;
if(c>d)
f[i]=d;
else if(c<d)
f[i]=c;
}
int i=0;
for(i=0;i<m-1;i++)
printf("%d\n",f[i]);
printf("%d",f[i]);
}
至此本题完全正确