ZCMU—1465

来源:互联网 发布:出货单打单软件 编辑:程序博客网 时间:2024/05/21 14:04

1465: Post office

Time Limit: 1 Sec  Memory Limit: 128 MB
[Submit][Status][Web Board]

Description

There are N(N<=1000) villages along a straight road, numbered from 1 to N for simplicity. We know exactly the position of every one (noted pos[i],pos[i] is positive integer and pos[i]<=10^8). The local authority wants to build a post office for the people living in the range i to j(inclusive). He wants to make the sum of |pos[k]-position_of_postoffice| (i<=k<=j) is minimum.

Input

For each test case, the first line is n. Then n integer, representing the position of every village and in acending order. Then a integer q (q<=200000), representing the queries. Following q lines, every line consists of two integers i and j. the input file is end with EOF. Total number of test case is no more than 10.Be careful, the position of two villages may be the same.

Output

For every query of each test case, you tell the minimum sum.

Sample Input

3
1 2 3
2
1 3
2 3

Sample Output

2
1

【分析】

题意:按顺序给你n个村庄在x轴上的位置,每个询问给你x,y两个村庄,让你在这两个村庄中间找一个村庄建一个邮箱,要求第x个和第y个村庄中间的所有村庄到这个邮箱的距离最短...
显然这个村庄就应该是这y-x+1个村庄的中间的那个村庄...也就是编号为(x+y)/2的那个村庄,然后就是算距离的问题了...暴力应该会超时否则也不会出这道题了
讲道理我觉得应该是树状数组的...但是2n的预处理算的清楚也可以做...因为预处理区间和之后是可以直接算出答案的...反而可能比树状数组来的快....
【代码】
#include <stdio.h>long long f[2000];long long a[2000];long long g[2000];int main()  {  int n;    while (~scanf("%d",&n)&& n)      {          f[0]=0;        for (int i=1;i<=n;i++)          {              scanf("%I64d",&a[i]);              f[i]=f[i-1]+a[i];          }          g[n+1]=0;        for (int i=n;i>=1;i--) g[i]=g[i+1]+a[i];          int m;scanf("%d",&m);          for (int i=0;i<m;i++)        {              int x,y;              scanf("%d%d",&x,&y);              int mid=(x+y)/2;              long long ans=(a[mid]*(mid-x)-(f[mid-1]-f[x-1]))+((g[mid+1]-g[y+1])-a[mid]*(y-mid));              printf("%lld\n",ans);          }      }      return 0;  }  


0 0
原创粉丝点击