您的位置:首页 > 移动开发

Sicily 1686 Happy Children's Day

2015-06-04 11:25 302 查看
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int MAXN = 100010;

//  declaration of the segment tree
struct STNode
{
int l, r, maxv, maxi;  //  left bound, right bound, max value, max index
int lazy;  //  delay value to update
STNode *lchild, *rchild;  //  pointer to left child and right child
}node[MAXN << 1], *root;

int z, value, Index;

//  build the segment tree
STNode* build(int l, int r)
{
STNode* tmp = &node[z++];
tmp->l = l, tmp->r = r, tmp->maxv = 0, tmp->maxi = l;
tmp->lazy = 0;
if (l == r)  //  the leaf nodes
{
tmp->lchild= tmp->rchild = NULL;
}
else
{
int mid = (l + r) >> 1;
tmp->lchild = build(l, mid);  //  build the left child tree
tmp->rchild = build(mid + 1, r);  //  build the right child tree
}
return tmp;
}

//  pass the dalay value
inline void PassLazy(STNode *root)
{
if (!root->lazy)
return;
root->lchild->lazy += root->lazy;
root->lchild->maxv += root->lazy;

root->rchild->lazy += root->lazy;
root->rchild->maxv += root->lazy;

root->lazy = 0;  //  clear the lazy value
}

//  update the segment tree
void update(STNode* root, int l, int r, int val)
{
//  find the position
if (root->l == l && root->r == r)
{
root->lazy += val;
root->maxv += val;
return ;
}
//  update the delay
PassLazy(root);
int mid = (root->l + root->r) >> 1;
if (r <= mid)  //  all in the left child tree
update(root->lchild, l, r, val);
else if (l > mid)  //  all in the right child tree
update(root->rchild, l, r, val);
else  //  in two trees
{
update(root->lchild, l, mid, val);
update(root->rchild, mid + 1, r, val);
}

//  update the max value and index
if (root->lchild->maxv >= root->rchild->maxv)
{
root->maxv = root->lchild->maxv;
root->maxi = root->lchild->maxi;
}
else
{
root->maxv = root->rchild->maxv;
root->maxi = root->rchild->maxi;
}
}

//  query the segment tree
void query(STNode* root, int l, int r)
{
//  find the position
if (root->l == l && root->r == r)
{
if (root->maxv > value)  //  compare the value with global variant
{
Index = root->maxi;
value = root->maxv;
}
return;
}
PassLazy(root);
int mid = (root->l + root->r) >> 1;
if (r <= mid)  //  all in left child tree
query(root->lchild, l, r);
else if (l > mid)  //  all in right child tree
query(root->rchild, l, r);
else  //  in two child trees
{
query(root->lchild, l, mid);
query(root->rchild, mid + 1, r);
}
}

int main()
{
int n, m;
while (scanf("%d%d", &n, &m) && n + m)
{
z = 0;
root = build(1, n);
while (m--)
{
char opt;
int x, y;
scanf("\n%c%d%d", &opt, &x, &y);
if (opt == 'I')
{
int v;
scanf("%d", &v);
update(root, x, y, v);
}
else
{
Index = value = -1;
query(root, x, y);
printf("%d\n", value);
update(root, Index, Index, -value);  //  update the value of the Index
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: