您的位置:首页 > 其它

ZCMU-1465-Post office

2017-02-03 10:46 155 查看

1465: Post office

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 112  Solved: 23

[Submit][Status][Web
Board]

Description

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.

Input

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.

Output

For every query of each test case, you tell the minimum sum.

Sample Input

3

1 2 3

2

1 3

2 3

Sample Output

2

1

【解析】
这道题的意思就是给我们n个村庄的位置,然后m次询问,问你在a到b的村庄中选一个村庄作为建立邮局的地方使距离
和最小。我们很快就能想到其实就是y-x+1个村庄当中的中间那个就是。所以我们需要算出那个村庄的编号其实就是
(x+y)/2,此处附上他人代码.以及自己的理解。值得学习。
#include<iostream>
#include<string>
#include <cstdio>
using namespace std;
long long f[1010];
long long a[1010];
long long g[1010];
int main()
{
int i,n,x,y,sum;
while (~scanf("%d",&n))
{
if(n==0)
break;
f[0]=0;
for (i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
f[i]=f[i-1]+a[i];//计算前面的区间和
}
g[n+1]=0;
for (i=n;i>=1;i--) g[i]=g[i+1]+a[i];//计算后面的
int m;scanf("%d",&m);
for (i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
int mid=(x+y)/2;//计算位置
sum=(a[mid]*(mid-x)-(f[mid-1]-f[x-1]))+((g[mid+1]-g[y+1])-a[mid]*(y-mid));
/*这里其实就是比如说a[mid]*(mid-x)表示有(mid-x)个点在这个区间当中,f[mid-1]-f[x-1]其实最后还
剩下的就是a[x]到a[mid-1]其实就是a[mid]-a[x]+a[mid]-a[x+1]....就是算距离和,后面的g[mid+1]-g[y+1]
其实还剩下的是a[mid+1]到a[y]其实就是a[mid+1]-a[mid]+a[mid+2]-a[mid]...就是算区间和的意思*/
printf("%lld\n",sum);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: