Post office
题目描述
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.
输入
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.
输出
For every query of each test case, you tell the minimum sum.
样例输入
3
1 2 3
2
1 3
2 3
样例输出
2
1
思路:很显然,邮局应该建在这j-i+1个村庄的最中间村庄,对区间距离求和我们使用树状数组!
代码如下:
#include "stdio.h"
#include "string.h" long long sum[]; long long Low(long long x)
{
return x&(-x);
} long long SUM(long long x) //树状数组求区间和
{
long long ans = ;
for(long long i=x; i>; i-=Low(i))
ans += sum[i];
return ans;
} int main()
{
long long n;
long long i,j,k;
long long x,y,Q;
long long mid;
while(scanf("%lld",&n)!=EOF)
{
memset(sum,,sizeof(sum));
for(i=; i<=n; ++i)
{
scanf("%lld",&k);
for(j=i; j<=n; j += Low(j))
sum[j] += k;
}
scanf("%lld",&Q);
while(Q--)
{
scanf("%lld %lld",&x,&y);
mid = x+(y-x+)/;
if((y-x+)%==)
printf("%lld\n",SUM(y)-SUM(mid-)-(SUM(mid-)-SUM(x-)));
else
printf("%lld\n",SUM(y)-SUM(mid)-(SUM(mid-)-SUM(x-)));
}
}
return ;
}