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 11 to NN 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 ii 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 nn.
Then nn integer,
representing the position of every village and in ascending order. Then a integer q(q≤200000)q(q≤200000),
representing the queries. Following qq lines,
every line consists of two integers ii and jj.
the input file is end with EOF. Total number of test case is no more
than 1010.
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);
}
}
}

本文介绍了一个关于邮局选址的问题,即如何确定最佳位置以使所有村庄到邮局的距离之和最小。通过分析村庄的位置分布,文章提供了一种解决策略,并附带了相应的代码实现。
2794

被折叠的 条评论
为什么被折叠?



