开始用链表写,可是申请空间导致无限MLE,蛋疼的无以复加
懒得写,默默剽窃个,自己写了注释
#include <stdio.h> typedef struct { int left,right,max; int lChild,rChild; }SegTree; SegTree list[800000];// int max(int a, int b)//求最大 { return a > b? a:b; } void createSegTree(int root, int left, int right) { int mid; if(right < left)//不在该区间 return; list[root].left = left; list[root].right = right; list[root].max = 0; mid = (left + right) / 2; if(right - left >= 1)//在区间内,但未找到 { list[root].lChild = root << 1;//左移按二进制进行翻倍 list[root].rChild = (root << 1) + 1; createSegTree(list[root].lChild, left, mid); createSegTree(list[root].rChild, mid + 1, right); } else{//找到了,将其孩子标志位-1 list[root].lChild = -1; list[root].rChild = -1; } } void updateSegTree(int root, int updateNum, int score) { int mid; mid = (list[root].left + list[root].right) / 2;//用于判断左右 if(list[root].left <= updateNum && updateNum <= list[root].right)//位于区间内 { list[root].max = max(list[root].max, score); if(list[root].lChild != -1 && updateNum <= mid) updateSegTree(list[root].lChild, updateNum, score);//查找左子树 else if(list[root].rChild != -1 && updateNum >= mid + 1) updateSegTree(list[root].rChild, updateNum, score); } } int queryHighestScore(int root, int left, int right) { int mid,ans; mid = (list[root].left + list[root].right) / 2;//算法类似于查询 if(list[root].left == left && list[root].right == right) return list[root].max; else if(list[root].lChild != -1 && right <= mid) ans = queryHighestScore(list[root].lChild, left, right); else if(list[root].rChild != -1 && left >= mid + 1) ans = queryHighestScore(list[root].rChild, left, right); else{ ans = queryHighestScore(list[root].lChild,left, mid); ans = max(ans, queryHighestScore(list[root].rChild, mid + 1, right)); } return ans; } int main () { char order; int i,N,M,score,left,right,root; // freopen("in.txt","r",stdin); while(~scanf("%d%d",&N,&M)) { root = 1; createSegTree(root,1,N); for(i = 1; i <= N; i++) { scanf("%d",&score); updateSegTree(root, i, score); } getchar(); for(i = 0; i < M; i++) { scanf("%c%d%d",&order,&left,&right); getchar(); if(order == 'Q') printf("%d ",queryHighestScore(root, left, right)); else updateSegTree(root, left, right); } } return 0; }