【Codevs】1082 线段树练习 3 && 线段树模板
2016-05-08 10:05
267 查看
没用的题面 –>
题目描述 Description
给你N个数,有两种操作:1:给区间[a,b]的所有数增加X 2:询问区间[a,b]的数的和。
输入描述 Input Description
第一行一个正整数n,接下来n行n个整数, 再接下来一个正整数Q,每行表示操作的个数, 如果第一个数是1,后接3个正整数, 表示在区间[a,b]内每个数增加X,如果是2, 表示操作2询问区间[a,b]的和是多少。
pascal选手请不要使用readln读入
输出描述 Output Description
对于每个询问输出一行一个答案样例输入 Sample Input
3 1 2 3 2 1 2 3 2 2 2 3
样例输出 Sample Output
9
数据范围及提示 Data Size & Hint
数据范围 1<=n<=200000 1<=q<=200000
代码– >
#include <iostream> #include <queue> #include <cstdio> #include <cstring> #define L(x) (x << 1) #define R(x) (x << 1 | 1) #define SZ(x) (tree[x].r - tree[x].l + 1) using namespace std; typedef long long LL; const int MAXN = 1999997; LL num[MAXN]; struct doc{ LL l, r, sum, add; }tree[MAXN << 2]; void update(LL p) { tree[p].sum = tree[L(p)].sum + tree[R(p)].sum; return ; } void build(LL p, LL l, LL r) { tree[p].l = l; tree[p].r = r; if(l == r) { tree[p].sum = num[l]; return ; } LL mid = (tree[p].l + tree[p].r) / 2; build(L(p),l,mid); build(R(p),mid + 1, r); update(p); return ; } void spread(LL p) { if(tree[p].add) { tree[L(p)].add += tree[p].add; tree[R(p)].add += tree[p].add; tree[L(p)].sum += (tree[p].add * SZ(L(p))); tree[R(p)].sum += (tree[p].add * SZ(R(p))); tree[p].add = 0; update(p); return ; } else return; } void change(LL l, LL r, LL p, LL x) { if(l <= tree[p].l && r >= tree[p].r) { tree[p].add += x; tree[p].sum += (SZ(p) * x); return ; } spread(p); LL mid = (tree[p].l + tree[p].r) / 2; if(l <= mid) change(l,r,L(p),x); if(r > mid) change(l,r,R(p),x); update(p); return; } LL ask(LL l, LL r, LL p) { if(l <= tree[p].l && r >= tree[p].r) return tree[p].sum; spread(p); LL mid = (tree[p].l + tree[p].r ) / 2; LL ans = 0; if(l <= mid) ans += ask(l,r,L(p)); if(r > mid) ans += ask(l,r,R(p)); update(p); return ans; } int main() { LL n, Q; scanf("%lld",&n); for(LL i = 1; i <= n; i ++) scanf("%lld",&num[i]); build(1,1,n); scanf("%lld",&Q); for(LL i = 1; i <= Q; i ++) { LL t; LL a,b,x; scanf("%lld",&t); if(t == 1) { scanf("%lld%lld%lld",&a,&b,&x); change(a,b,1,x); } else if(t == 2) { scanf("%lld%lld",&a,&b); printf("%lld\n",ask(a,b,1)); } } return 0; }
相关文章推荐
- 设计模式之行为型模式 - 调用行为的传递问题
- [div+css]晒晒最新制作专题推广页模板
- 2008大学生入党申请书 模板
- C#数据结构之顺序表(SeqList)实例详解
- Lua教程(七):数据结构详解
- IMAIL多语言模板两套Outlook&Gmail模板下载
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- 数据结构之Treap详解
- 在PHP中使用模板的方法
- 深入解析php模板技术原理【一】
- Json2Template.js 基于jquery的插件 绑定JavaScript对象到Html模板中
- 在ASP中不用模板生成HTML静态页直接生成.html页面
- 基于HTML模板和JSON数据的JavaScript交互(移动端)
- 用C语言举例讲解数据结构中的算法复杂度结与顺序表
- C#模板方法模式(Template Method Pattern)实例教程
- C#数据结构之堆栈(Stack)实例详解
- C#数据结构之双向链表(DbLinkList)实例详解