Post-office 树状数组
来源:互联网 发布:淘宝兼职刷单是真的吗 编辑:程序博客网 时间:2024/06/05 03:26
Post office
题目描述
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.
输入
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.
输出
For every query of each test case, you tell the minimum sum.
样例输入
31 2 321 32 3
样例输出
21
思路:很显然,邮局应该建在这j-i+1个村庄的最中间村庄,对区间距离求和我们使用树状数组!
代码如下:
#include "stdio.h"#include "string.h"long long sum[1005];long long Low(long long x) { return x&(-x);}long long SUM(long long x) //树状数组求区间和{ long long ans = 0; for(long long i=x; i>0; i-=Low(i)) ans += sum[i]; return ans;}int main(){ long long n; long long i,j,k; long long x,y,Q; long long mid; while(scanf("%lld",&n)!=EOF) { memset(sum,0,sizeof(sum)); for(i=1; i<=n; ++i) { scanf("%lld",&k); for(j=i; j<=n; j += Low(j)) sum[j] += k; } scanf("%lld",&Q); while(Q--) { scanf("%lld %lld",&x,&y); mid = x+(y-x+1)/2; if((y-x+1)%2==0) printf("%lld\n",SUM(y)-SUM(mid-1)-(SUM(mid-1)-SUM(x-1))); else printf("%lld\n",SUM(y)-SUM(mid)-(SUM(mid-1)-SUM(x-1))); } } return 0;}
- Post-office 树状数组
- Post Office
- Post Office
- Post Office
- Post Office
- pku 1160 Post Office
- POJ 1160 Post Office
- pku 1160 Post Office
- pku1160 Post Office
- PKU1190 post office
- poj 1160 Post Office
- POJ 1160 Post Office
- DP: Post Office
- Post Office (P1160)
- poj 1160 Post Office
- poj1160(Post Office)
- POJ 1160 Post Office
- POJ 1160 Post Office
- JSP内置对象讲解
- php中安全模式safe_mode配置教程--不理解,从未接触过
- jsp常见状态代码
- iptables 添加,删除,查看,修改
- OpenLDAP服务器的学习
- Post-office 树状数组
- 使用WebStorm开发TypeScript的设置
- 四叉树空间索引原理及其实现
- 数据分析(一)
- java经典排序算法
- Thinkpad W520 完美安装Ubuntu14.04LTS
- 移动平台3G手机网站前端开发布局技巧汇总
- Discuz X3整合ECShop同步登录登出问题解决方案
- 追求神乎其技的程式设计之道