hdu 1754 简单的线段树应用

本来想找些树状数组的题做做,看到这题,不知道用树状数组的话应该如何做,就还是用线段树了。

/*
* hdu1754/win.cpp
* Created on: 2011-9-6
* Author : ben
*/
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<cmath>
#include
<algorithm>
using namespace std;

const int MAXN = 200100;
const int MAX_NODE = 400100;
int N, M, nCount;
int scores[MAXN];

typedef
struct CNode {
int L, R;
int maxscore;
CNode
*pLeft, *pRight;
} CNode;

CNode Tree[MAX_NODE];

inline
int mymax(int a, int b) {
return a > b ? a : b;
}

//建立线段树
void BuildTree(CNode *pRoot, int L, int R) {
pRoot
->L = L;
pRoot
->R = R;
if (L == R) {
pRoot
->maxscore = scores[L];
return;
}
nCount
++;
pRoot
->pLeft = Tree + nCount;
nCount
++;
pRoot
->pRight = Tree + nCount;
int mid = (L + R) / 2;
BuildTree(pRoot
->pLeft, L, mid);
BuildTree(pRoot
->pRight, mid + 1, R);
pRoot
->maxscore = mymax(pRoot->pLeft->maxscore, pRoot->pRight->maxscore);
}

//插入数据
void Update(CNode *pRoot, int index) {
if (pRoot->L == pRoot->R) {
pRoot
->maxscore = scores[index];
return;
}
int mid = (pRoot->L + pRoot->R) / 2;
if (index <= mid) {
Update(pRoot
->pLeft, index);
}
else {
Update(pRoot
->pRight, index);
}
pRoot
->maxscore = mymax(pRoot->pLeft->maxscore, pRoot->pRight->maxscore);
}

int Query(CNode *pRoot, int from, int to) {
if (pRoot->L == from && pRoot->R == to) {
return pRoot->maxscore;
}
int mid = (pRoot->L + pRoot->R) / 2;
if (mid >= from && mid < to) {
int m1, m2;
m1
= Query(pRoot->pLeft, from, mid);
m2
= Query(pRoot->pRight, mid + 1, to);
return mymax(m1, m2);
}
else if (mid >= to) {
return Query(pRoot->pLeft, from, to);
}
else {
return Query(pRoot->pRight, from, to);
}
}

void work();
int main() {
#ifndef ONLINE_JUDGE
freopen(
"data.in", "r", stdin);
#endif
work();
return 0;
}

void work() {
char op;
int a, b;
while (scanf("%d%d", &N, &M) == 2) {
for (int i = 1; i <= N; i++) {
scanf(
"%d", &scores[i]);
}
nCount
= 0;
BuildTree(Tree,
1, N);
for (int i = 0; i < M; i++) {
scanf(
" %c", &op);
if (op == 'Q') {
scanf(
"%d%d", &a, &b);
printf(
"%d\n", Query(Tree, a, b));
}
else {
scanf(
"%d%d", &a, &b);
scores[a]
= b;
Update(Tree, a);
}
}
}
}

  

posted @ 2011-09-06 17:09  moonbay  阅读(143)  评论(0编辑  收藏  举报