[HDU 6315] Naive Operations
[题目链接]
http://acm.hdu.edu.cn/showproblem.php?pid=6315
[算法]
线段树
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXN 100010 int i,n,q,l,r; int b[MAXN]; char op[10]; struct SegmentTree { struct Node { int l,r; int sum,val; int tag; } Tree[MAXN << 2]; inline void update(int index) { Tree[index].val = min(Tree[index << 1].val,Tree[index << 1 | 1].val); Tree[index].sum = Tree[index << 1].sum + Tree[index << 1 | 1].sum; } inline void pushdown(int index) { if (Tree[index].tag) { Tree[index << 1].val -= Tree[index].tag; Tree[index << 1 | 1].val -= Tree[index].tag; Tree[index << 1].tag += Tree[index].tag; Tree[index << 1 | 1].tag += Tree[index].tag; Tree[index].tag = 0; } } inline void build(int index,int l,int r) { int mid; Tree[index].l = l; Tree[index].r = r; Tree[index].sum = 0; Tree[index].tag = 0; if (l == r) { Tree[index].val = b[l]; return; } mid = (l + r) >> 1; build(index << 1,l,mid); build(index << 1 | 1,mid + 1,r); update(index); } inline void modify(int index,int l,int r) { int mid; if (l == r) { Tree[index].val = b[l]; Tree[index].sum++; return; } pushdown(index); mid = (Tree[index].l + Tree[index].r) >> 1; if (!Tree[index << 1].val) modify(index << 1,l,mid); if (!Tree[index << 1 | 1].val) modify(index << 1 | 1,mid + 1,r); update(index); } inline void add(int index,int l,int r) { int mid; if (Tree[index].l == l && Tree[index].r == r) { Tree[index].val--; Tree[index].tag++; if (Tree[index].val == 0) modify(index,l,r); return; } pushdown(index); mid = (Tree[index].l + Tree[index].r) >> 1; if (mid >= r) add(index << 1,l,r); else if (mid + 1 <= l) add(index << 1 | 1,l,r); else { add(index << 1,l,mid); add(index << 1 | 1,mid + 1,r); } update(index); } inline int query(int index,int l,int r) { int mid; if (Tree[index].l == l && Tree[index].r == r) return Tree[index].sum; pushdown(index); mid = (Tree[index].l + Tree[index].r) >> 1; if (mid >= r) return query(index << 1,l,r); else if (mid + 1 <= l) return query(index << 1 | 1,l,r); else return query(index << 1,l,mid) + query(index << 1 | 1,mid + 1,r); } } T; int main() { while (scanf("%d%d",&n,&q) != EOF) { for (i = 1; i <= n; i++) scanf("%d",&b[i]); T.build(1,1,n); while (q--) { scanf("%s",&op); if (strcmp(op,"add") == 0) { scanf("%d%d",&l,&r); T.add(1,l,r); } else { scanf("%d%d",&l,&r); printf("%d\n",T.query(1,l,r)); } } } return 0; }