题意是求一个环上的两点之间最短距离,纯粹模拟,最后一点超时,过不了。后来经人提示,不用保存各点的值,只要保存从起点到该点的值,即可。
代码:
//1046 18:30 -19:14 #include<stdio.h> const int NUM=200008; int a[NUM]; int main() { int n,i,m,x,y,j; //freopen("C:\\Documents and Settings\\Administrator\\桌面\\input.txt","r",stdin); scanf("%d",&n); int ans=0,temp,suma=0; for(i=1;i<=n;i++){ scanf("%d",&a[i]); a[i+n]=a[i]; ans+=a[i]; } scanf("%d",&m); while(m--){ suma=0; scanf("%d%d",&x,&y); if(x>y){ temp=y; y=x; x=temp; } if(y-x<=n-y+x){ for(i=x;i<y;i++){ suma+=a[i]; } } else { for(i=y;i<n+x;i++){ suma+=a[i]; } } if(suma<=ans-suma) printf("%d\n",suma); else printf("%d\n",ans-suma); } return 0; }
AC代码:
//1046 18:30 -19:14 #include<stdio.h> const int NUM=200008; int a[NUM]; int main() { int n,i,m,x,y,j; //freopen("C:\\Documents and Settings\\Administrator\\桌面\\input.txt","r",stdin); scanf("%d",&n); int ans=0,temp,suma=0; a[0]=0; for(i=1;i<=n;i++){ scanf("%d",&a[i]); ans+=a[i]; a[i]+=a[i-1]; /* a[i+n]=a[i];*/ } scanf("%d",&m); while(m--){ suma=0; scanf("%d%d",&x,&y); if(x>y){ temp=y; y=x; x=temp; } suma=a[y-1]-a[x-1]; // if(y-x<=n-y+x){ // suma=a[y] // } else { // for(i=y;i<n+x;i++){ // suma+=a[i]; // } // } if(suma<=ans-suma) printf("%d\n",suma); else printf("%d\n",ans-suma); } return 0; }