# 1046 Shortest Distance （20 分）

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 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 Mlines 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>
#include<algorithm>
using namespace std;

const int MAX = 100005;
int A[MAX],dis[MAX];//全局数组或静态数组未初始化，自动填充零；局部数组未初始化，将用随机数填充
//dis数组用于存放i节点顺时针到下一个节点的距离
//这样每次查询left-right，结果就是dis（right，left）和sum-dis（right，left）之间的最小值
int main(int argc, char const *argv[])
{
int N,M,sum = 0,left,right;
scanf("%d",&N);

for (int i = 1; i <= N; ++i)
{
scanf("%d", &A[i]);
sum += A[i];//累加sum
dis[i] = sum;//预处理dis
//在每次读入的时候，就进行累加，将查询的复杂度由O(n)降到O(1)
//如果不这样，遇到极端的情况，就会发生，查询时遍历整个数组需要10^5和有10^4次查询，就会产生10^9次操作，超过100ms的时间（1s能承受的运算算次数一般为10^7~10^8）
}

scanf("%d",&M);
for (int i = 0; i < M; ++i)
{
scanf("%d%d", &left, &right);
if(left >right) swap(left,right);//查询时，会有left大于right的情况，这时就交换它们的位置
int temp = dis[right-1]-dis[left-1];
printf("%d\n",min(temp, sum-temp));
}

return 0;
}

#include<stdio.h>
int main()
{
int i,N,M,a[100001],b[10001][2],dist[100001],from,to,num,sum;
scanf("%d",&N);
sum=0;
dist[1]=0;
for(i=1;i<=N;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
dist[i+1]=dist[i]+a[i];
}
scanf("%d",&M);
for(i=1;i<=M;i++)
scanf("%d%d",&b[i][0],&b[i][1]);
for(i=1;i<=M;i++)
{
num=0;
from=b[i][0];
to=b[i][1];
if(from>to)  num+=dist[from]-dist[to];
else            num+=dist[to]-dist[from];
if(num<=sum/2)
printf("%d\n",num);
else
printf("%d\n",sum-num);
}
}