线段树模板(求最大最小)
2017-08-23 10:17
316 查看
#include<cstdio> const int INF = 0xffffff0; const long long IINF = 1e18; int minV = INF; int maxV = -INF; int max(int &a, int &b) { return a > b ? a : b; } int min(int &a, int &b) { return a < b ? a : b; } struct Node//不要左右子节点指针的做法 { int L, R; int minV, maxV; int Mid() { return (L + R) / 2; } }tree[800000];//4倍叶子节点的数量就够 void BuildTree(int root, int L, int R) { tree[root].L = L; tree[root].R = R; tree[root].minV = INF; tree[root].maxV = -INF; if (L != R) { BuildTree(2 * root + 1, L, (L + R) / 2); BuildTree(2 * root + 2, (L + R) / 2 + 1, R); } } void Insert(int root, int i, int v)//将第i个数,其值为v,插入线段树 { if (tree[root].L == tree[root].R) { tree[root].minV = tree[root].maxV = v; return; } tree[root].minV = min(tree[root].minV, v); tree[root].maxV = max(tree[root].maxV, v); if (i <= tree[root].Mid())Insert(2 * root + 1, i, v); else Insert(2 * root + 2, i, v); } void Query(int root, int s, int e)//查询区间[s,e]中的最小值和最大值,如果更优就记录在全 { if (tree[root].minV >= minV&&tree[root].maxV <= maxV) { return; } if (tree[root].L == s&&tree[root].R == e) { minV = min(minV, tree[root].minV); maxV = max(maxV, tree[root].maxV); return; } if (e <= tree[root].Mid())Query(2 * root + 1, s, e); else if (s > tree[root].Mid())Query(2 * root + 2, s, e); else { Query(2 * root + 1, s, tree[root].Mid()); Query(2 * root + 2, tree[root].Mid() + 1, e); } } int main() { int n, q, h; int i, j, k; while (scanf("%d%d", &n, &q)) { BuildTree(0, 1, n); for (int i = 1; i <= n; i++) { scanf("%d", &h); Insert(0, i, h); } for (int i = 0; i < q; i++) { int s, e; char ch[3]; scanf("%s", ch); if (ch[0] == 'Q') { scanf("%d%d", &s, &e); minV = INF; maxV = -INF; Query(0, s, e); printf("%d\n", maxV); } else { scanf("%d%d", &s, &e); Insert(0, s, e); } } } return 0; }
相关文章推荐
- 模板:线段树求区间最大/最小值及下标
- POJ 3264 Balanced Lineup(线段树点修改 查询最大最小总和 修改 增加/模板)
- 线段树区间更新,区间求和,最大值,最小值模板
- 【南阳OJ 119】士兵杀敌(三)(线段树)(最大值&最小值问题 模板题)
- NYOJ 1185-最大最小值【线段树:模板--学习ing】
- HDU 1754 B I Hate It 线段树 单点更新 区间最大值 模板
- poj 2987 最大权闭合图 最大流最小割模板
- 模板_matlab 匈牙利算法(最大匹配数/最小覆盖点)
- 线段树模板(区间和最大值最下值)
- POJ 3264(线段树求区间内最大值和最小值)
- [最小环 最小环计数 最大平均环 模板题] POJ 1734 Sightseeing trip & FZU 2090 旅行社的烦恼 & POJ 2949 Word Rings
- POJ 3264 Balanced Lineup(最大最小差值 线段树水题)
- 模板:各类型的最大数和最小数表示
- HDU 1754 B I Hate It 线段树 单点更新 区间最大值 模板
- HDU 1754 I Hate it (线段树最大值模板)
- 2017 icpc 南宁赛区 F.Overlapping Rectangles(重叠矩形的最大面积+线段树模板)
- HDU 1754 B I Hate It 线段树 单点更新 区间最大值 模板
- hdu 3374 next表,最大最小表示法模板
- HDU 1754 B I Hate It 线段树 单点更新 区间最大值 模板
- Dinic模板(最大流最小割)