題目描述
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.
輸入描述
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 D?1?? D?2?? ? D?N??, where D?i?? is the distance between the i-th and the (i+1)-st exits, and D?N?? 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 (≤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??.
輸出描述
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
輸入例子
5 1 2 4 14 9
3
1 3
2 5
4 1
輸出例子
3
10
7
我的代碼
#include<stdio.h>
#define N 20000
int main(){
int n,m,i,j,d[N],a[N],b[N],sum=0,sum1=0,sum2=0;
scanf("%d",&n); //輸入N
for(i=1;i<=n;i++){ //從1開(kāi)始輸入
scanf("%d",&d[i]);
sum=sum+d[i]; //計(jì)算所有長(zhǎng)度的和
}
scanf("%d",&m); //輸入M
for(i=1;i<=m;i++){ //從1開(kāi)始記組數(shù)
scanf("%d %d",&a[i],&b[i]);
}
for(i=1;i<=m;i++){
for(j=a[i]<b[i]?a[i]:b[i];j<=((a[i]>b[i]?a[i]:b[i])-1);j++){
sum1=sum1+d[j]; //計(jì)算順時(shí)針的距離
}
sum2=sum-sum1; //得到逆時(shí)針的距離
if(sum1>=sum2){
printf("%d\n",sum2);
}
else{
printf("%d\n",sum1);
}
sum1=sum2=0; //重置sun1與sum2
}
return 0;
}
我的分析
這道題的英文描述不是很容易翻譯叉庐,但是多讀幾遍題目理解之后還算是比較簡(jiǎn)單的題获诈。我的思路是比較暴力的一種幢码,就是先計(jì)算出兩個(gè)結(jié)點(diǎn)(按照結(jié)點(diǎn)的序號(hào)由低到高)順時(shí)針之間的距離sum1,然后拿整個(gè)圈的總距離sum-sum1得到sum2郎笆,最后比較輸出sum1與sum2之間小的那個(gè)數(shù)即可。但是我這樣的算法并不是滿分,主要原因是如果對(duì)數(shù)組定義的大小不夠的話容易發(fā)生段錯(cuò)誤澈吨,過(guò)大的話則會(huì)超時(shí)。
AC代碼
#include<stdio.h>
#define N 100005
int main(){
int n,m,i,j,t,len[N],d[N],a[N],b[N],sum=0,sum1=0,sum2=0; //新定義了一個(gè)len[]數(shù)組
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&d[i]);
sum=sum+d[i];
len[i]=sum; //len[i]表示第i+1個(gè)節(jié)點(diǎn)到第1個(gè)節(jié)點(diǎn)之間的距離
}
scanf("%d",&m);
for(i=1;i<=m;i++){ //在一個(gè)循環(huán)里面進(jìn)行輸入與計(jì)算
scanf("%d %d",&a[i],&b[i]);
if(a[i]<b[i]){
t=a[i];
a[i]=b[i];
b[i]=t;
}
sum1=len[a[i]-1]-len[b[i]-1];
sum2=sum-sum1;
if(sum1>=sum2){
printf("%d\n",sum2);
}
else{
printf("%d\n",sum1);
}
sum1=sum2=0;
}
return 0;
}