线段树
Posted downrainsun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线段树相关的知识,希望对你有一定的参考价值。
求区间最大值
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxmnode = 1 << 18; const int maxm = 5e4 + 5; struct NODE { int value; int left, right; } node[maxmnode]; int index[maxm]; void buildtree(int i, int left, int right) { node[i].left = left; node[i].right = right; node[i].value = 0; if(left == right) { index[left] = i; return; } buildtree(i << 1, left, (int)(floor(left + right) / 2.0)); buildtree((i << 1) + 1, (int)(floor(left + right) / 2.0) + 1, right); } void updatetree(int ri) { if(ri == 1) return; int fi = ri / 2; int a = node[fi << 1].value; int b = node[ (fi << 1) + 1 ].value; node[fi].value = max(a, b); updatetree(fi); } int MAX; void query(int i, int l, int r) { if(node[i].left == l && node[i].right == r) { MAX = max(MAX, node[i].value); return; } i = i << 1; if(l <= node[i].right) { if(r <= node[i].right) query(i, l, r); else query(i, l ,node[i].right); } i++; if(r >= node[i].left) { if(l >= node[i].left) query(i, l, r); else query(i, node[i].left, r); } } int main() { int n, m, q; while(~scanf("%d%d", &n, &m)) { buildtree(1, 1, n); for(int i = 1; i <= n; i++) { scanf("%d", &q); node[ index[i] ].value = q; updatetree(index[i]); } char ch[10]; int a,b; while(m--) { scanf("%s%d%d", ch, &a, &b); if(ch[0] == ‘Q‘) { MAX = 0; query(1, a, b); printf("%d ", MAX); } else { node[ index[a] ].value = b;//值无所谓,b; updatetree(index[a]); } } } return 0; }
以上是关于线段树的主要内容,如果未能解决你的问题,请参考以下文章