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 |
#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);
}
}
}