[POJ3264]Balanced Lineup(线段树,区间最值差)
2016-04-26 21:50
417 查看
题目链接:http://poj.org/problem?id=3264
一排牛按1~n标号记录重量,问每个区间最重的和最轻的差值。
线段树维护当前节点下属叶节点的两个最值,查询后作差即可。
一排牛按1~n标号记录重量,问每个区间最重的和最轻的差值。
线段树维护当前节点下属叶节点的两个最值,查询后作差即可。
#include <algorithm> #include <iostream> #include <iomanip> #include <cstring> #include <climits> #include <complex> #include <fstream> #include <cassert> #include <cstdio> #include <bitset> #include <vector> #include <deque> #include <queue> #include <stack> #include <ctime> #include <set> #include <map> #include <cmath> using namespace std; #define lson l, m, rt << 1 #define rson m + 1, r, rt << 1 | 1 typedef pair<int, int> pii; const int maxn = 50050; int n, q, a, b; pii node[maxn<<2]; void pushUP(int rt) { int ll = min(node[rt<<1].first, node[rt<<1|1].first); int rr = max(node[rt<<1].second, node[rt<<1|1].second); node[rt] = pii(ll, rr); } void build(int l, int r, int rt) { if(l == r) { scanf("%d", &node[rt].first); node[rt].second = node[rt].first; return; } int m = (l + r) >> 1; build(lson); build(rson); pushUP(rt); } int querymax(int L, int R, int l, int r, int rt) { if(L <= l && r <= R) { return node[rt].second; } int m = (l + r) >> 1; int ans = -1; if(L <= m) ans = max(ans, querymax(L, R, lson)); if(m < R) ans = max(ans, querymax(L, R, rson)); return ans; } int querymin(int L, int R, int l, int r, int rt) { if(L <= l && r <= R) { return node[rt].first; } int m = (l + r) >> 1; int ans = 0x7f7f7f; if(L <= m) ans = min(ans, querymin(L, R, lson)); if(m < R) ans = min(ans, querymin(L, R, rson)); return ans; } int main() { // freopen("in", "r", stdin); while(~scanf("%d %d", &n, &q)) { build(1, n, 1); while(q--) { scanf("%d %d", &a, &b); int ll = querymin(a, b, 1, n, 1); int rr = querymax(a, b, 1, n, 1); printf("%d\n", rr - ll); } } return 0; }
相关文章推荐
- 约瑟夫环
- 这是自己目前的第一份博客
- 关于格式控制 实例:格式化输出浮点数
- Codewars-Javascript训练手册:Date 对象
- zoj5093Battle ships【二分图 棋盘覆盖有断点】
- 关于格式控制 实例:不同基数形式的输入/输出
- OpenCV3.0 HOG+SVM行人检测器
- LeetCode 4, Median of Two Sorted Arrays
- Julia: MFDCCA和MFCCA算法代码,难受!
- zoj1115 Digital Roots
- OOP学习2
- C#几个快捷键
- C++学习笔记之——引用 内联函数
- 软件需求工程(摘抄)
- aa
- scikit-learn学习之贝叶斯分类算法
- 【leetcode】84. Largest Rectangle in Histogram
- Oracle EBS登陆后,直接打开某个特定Form或Page
- Android UI基础——ViewPager+Fragment
- java 接口和抽象类