Post office
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
There are N(N≤1000) N(N≤1000) villages along a straight road, numbered from 1 1 to N N for simplicity. We know exactly the position of every one (noted pos [i] [i],pos [i] [i] is positive integer and pos [i]≤108 [i]≤108). The local authority wants to build a post office for the people living in the range i i to j(inclusive). He wants to make the sum of |pos [k]− [k]−position_of_postoffice| (i≤k≤j) (i≤k≤j) is minimum.
Input
For each test case, the first line is
n
n. Then
n
n integer, representing the position of every village and in ascending order. Then a integer
q(q≤200000)
q(q≤200000), representing the queries. Following
q
q lines, every line consists of two integers
i
i and
j
j. the input file is end with EOF
. Total number of test case is no more than
10
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 and output
Sample Input | Sample Output |
---|---|
3 1 2 3 2 1 3 2 3 | 2 1 |
Hint
Huge input,scanf
is recommend.
题意:在一条直线上有n个村庄,他们在x轴上是坐标严格递增,现有q次询问,每次询问给出a、b两个村庄的序号,问在[ a , b ]中哪个村庄建立邮局
能使其他村庄的村民来邮局的路程之和最小。
显然,邮局设在每两个村庄之间的任意村庄对这两个村庄到邮局距离的加和是没有影响的,所以我们只要尽量让邮局靠中间即可。
#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[10001];
int main(){
while(scanf("%d", &n) == 1){
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
scanf("%d", &m);
while(m--){
int l, r;
int ans = 0;
scanf("%d%d", &l, &r);
while(l <= r){
ans += a[r]-a[l];
r--, l++;
}
printf("%d\n", ans);
}
}
}