uva 11054 Gerovia的酒交易(贪心+树状数组)
2015-06-15 14:05
369 查看
直线上有n个等距的村庄,每个村庄要么买酒,要么卖酒。把k个单位的酒从一个村庄运到相邻村庄需要k个单位的劳动力。问最少需要多少劳动力才能满足所有村庄的需求
思路贪心
思路贪心
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<iostream> #include<algorithm> #include<vector> #include<map> #include<queue> #include<stack> #include<string> #include<map> #include<set> #define eps 1e-6 #define LL long long using namespace std; const int maxn = 100000 + 100; const int INF = 0x3f3f3f3f; //freopen("input.txt", "r", stdin); int C[maxn], n; int lowbit(int x) { return x&(-x);} int sum(int x) { if(x == 0) return 0; int ret = 0; while(x > 0) { ret += C[x]; x -= lowbit(x); } return ret; } void add(int x, int d) { while(x <= n) { C[x] += d; x += lowbit(x); } } LL solve(int left, int right) { if(left == right) return (LL)0; if(left+1 == right) return (LL)abs(sum(right)-sum(left)); int mid = (left + right) >> 1; int tmp = sum(mid) - sum(left-1); add(mid, -tmp); add(mid+1, tmp); return solve(left, mid) + solve(mid+1, right) + (LL)abs(tmp); } void init() { memset(C, 0, sizeof(C)); int tmp; for(int i = 1; i <= n; i++) { cin >> tmp; add(i, tmp); } } int main() { //freopen("input.txt", "r", stdin); while(scanf("%d", &n) == 1 && n) { init(); cout << solve(1, n) << endl; } return 0; }
相关文章推荐
- Python_Python2_文件读取时的编码问题
- oracle存储过程入门
- Laravel -服务器配置-2
- iOS开发- UITabBarItem自定义图片
- 网狐游戏下载失败
- JAVA设计模式之单例模式
- ubuntu12.04 安装配置jdk1.7
- 打印出1-10000之间的所有对称数(如121,1331,2442)。
- 欢迎使用CSDN-markdown编辑器
- 2015 湘潭邀请赛 Fraction
- 语义网技术(2):jena的使用——更多示例和代码分析(上,例子从例2-例5)
- sql优化技巧
- IOS开发之利用通知(NSNotification)进行数据传递
- LeetCode Contains Duplicate III
- Linux 性能监测:工具
- hibernate+mysql,注解方式,自动添加创建,更新时间
- root script (root.sh or rootupgrade.sh) Failed to start resource ora.ons
- [JQ权威指南]第四天:使用JQ属性过滤器选择元素
- GRE填空词汇——冲突类
- Java多线程理解