简单题,但是自己最开始写的最后一个点没过,超时了
每次求距离求出来一个就可以了,另外一个方向的用总的距离减去就出来了
然鹅这么写了还是会超时
所以求第一个方向的距离也不能用循环
↓最有一个点超时
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
int n, m;
int arr[11000][11000];
int sum;
int main(){
scanf("%d",&n);
for(int i=1; i<=n; i++){
int w;
scanf("%d",&w);
sum += w;
if(i!=n) arr[i][i+1]= w;
else arr[i][1]= w;
}
scanf("%d",&m);
for(int i=0; i<m; i++){
int a, b, x, y;
scanf("%d%d",&x, &y);
a = min(x,y); b = max(x,y);
int sum1 = 0, sum2 = 0;
for(int j=a; j<b; j++)
sum1 += arr[j][j+1];
/*for(int k=a; k != b; k--){
if(k==1){
sum2 += arr[n][1];
k = n+1;
}
else sum2 += arr[k][k-1];
if(sum2 > sum1) break;
}*/
sum2 = sum - sum1;
printf("%d\n",min(sum1,sum2));
}
return 0;
}
简洁代码,直接最开始求和,用差值算
↓
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
int n, m;
int arr[110000];
int sum;
int main(){
scanf("%d",&n);
for(int i=1; i<=n; i++){
int w;
scanf("%d",&w);
sum += w;
arr[i] = sum;
}
scanf("%d",&m);
for(int i=0; i<m; i++){
int a, b, x, y;
scanf("%d%d",&x, &y);
a = min(x,y); b = max(x,y);
int sum1, sum2;
sum1 = arr[b-1] - arr[a-1];
sum2 = sum - sum1;
printf("%d\n",min(sum1,sum2));
}
return 0;
}
昨晚有点吓到了,,1044还没记笔记,,呵,,
七夕