HDU 1754 I Hate It(树状数组维护最值)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1754

        这道题用树状数组写的话就需要另外开一个数组来维护区间的最大值,a数组用来记录每个叶子结点的值,用c数组来记录最大值。因为更新操作是将x位置的值改为y,所以对于更新操作,我们只需要让它进Add函数就好了。查找遍历的时候,我们只需要查找比较区间里c数组里的最大值就行了,最后还要比较一下端点的a的值。


AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 200005
using namespace std;
int a[maxn],c[maxn];
int n,m;
string str;

int lowbit(int x){return x & (-x);}

void Add(int x,int ans){
  a[x] = ans;
  for(int i=x;i<=n;i+=lowbit(i)){
    c[i] = max(c[i], ans);
  }
}

int Query(int x,int y){
  int ans = a[y];
  while(x != y){
    for(y-=1; y-lowbit(y) >= x; y -= lowbit(y)){
      ans = max(ans, c[y]);
    }
    ans = max(ans, a[y]);
  }
  return ans;
}

int main()
{
  while(~scanf("%d%d",&n,&m)){
    memset(c,0,sizeof(c));
    for(int i=1;i<=n;i++){
      int index;
      scanf("%d",&index);
      Add(i, index);
    }
    while(m--){
      cin>>str;
      if(str == "U"){
        int x,y;
        scanf("%d%d",&x,&y);
        Add(x,y);
      }
      else{
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",Query(x,y));
      }
    }
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/charles_zaqdt/article/details/81094197
今日推荐