UESTC 929Post office(贪心)

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

Post office

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
 

There are N(N1000)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| (ikj)(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(q200000)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);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值