ZCMU-1465-Post office
2017-02-03 10:46
155 查看
1465: Post office
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 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 officefor 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 iand 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
31 2 3
2
1 3
2 3
Sample Output
21
【解析】
这道题的意思就是给我们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; }
相关文章推荐
- ZCMU—1465
- hdu 1465
- hdu 1465 不容易系列之一
- 杭电1465
- hduoj1465,不容易系列一,水题,递推求解
- ZOJ 1136 Multiple BFS 取模 POJ 1465
- poj 1465 bfs,余数判重
- Ural 1465. Pawn Game nim博弈
- POJ:1465 Multiple(bfs+剪枝)
- 题目1465:最简真分数
- poj 1160 Post Office
- POJ 1160Post Office
- ACM POJ 1160 Post Office
- POJ1160--Post Office(四边形不等式优化)
- 杭电1465 不容易系列之一
- HDOJ 1465 不容易系列之一 【错排公式 递推】
- POJ 1465 Multiple(用BFS求能组成的n的最小倍数)
- hdu 1465 错排问题(递归问题)
- hdu 1465 不容易系列之一
- POJ 1465-Multiple(BFS-最小整倍数)