[线段树] LightOJ 1135 - Count the Multiples of 3
来源:互联网 发布:微软程序员年薪 编辑:程序博客网 时间:2024/06/05 07:00
1135 - Count the Multiples of 3
题意:维护一个序列,长度为n,初始值都为0。两种操作: (0 l r) 表示[l, r]这段所有数加1,(1 l r) 表示询问[l, r]这段有多少数是3的倍数。
题解:使用带lazy的线段树维护。叶子节点维护在序列中的值,非叶子节点[l, r]维护lazy值,和3个数,分别表示mod 3 后余数为0,1,2的节点个数,那么被第一种操作覆盖的节点就是着3个值的循环位移。对于询问,输出表示0的值就行了。
#include<stdio.h>#define lson rt<<1, l, mid#define rson rt<<1|1, mid+1, rconst int N = 1e5+5;int sum[N<<2][3], lazy[N<<2];void push_up(int rt){ for(int i = 0; i < 3; ++i) sum[rt][i] = sum[rt<<1][i] + sum[rt<<1|1][i];}void build(int rt, int l, int r){ lazy[rt] = 0; sum[rt][0] = sum[rt][1] = sum[rt][2] = 0; if(l == r){ sum[rt][0] = 1; return; } int mid = (l+r) >> 1; build(lson); build(rson); push_up(rt);}void rote(int rt, int k){ int tmp[3]; for(int i = 0; i < 3; ++i) tmp[i] = sum[rt][i]; for(int i = 0; i < 3; ++i) sum[rt][i] = tmp[(i-k+3)%3];}void push_down(int rt, int l, int r){ if(lazy[rt]){ lazy[rt] %= 3; rote(rt<<1, lazy[rt]), rote(rt<<1|1, lazy[rt]); lazy[rt<<1] += lazy[rt], lazy[rt<<1|1] += lazy[rt]; lazy[rt] = 0; }}void update(int rt, int l, int r, int ql, int qr){ if(ql <= l && qr >= r){ lazy[rt] += 1; rote(rt, 1); return; } push_down(rt); int mid = (l+r) >> 1; if(ql <= mid) update(lson, ql, qr); if(qr > mid) update(rson, ql, qr); push_up(rt);}int query(int rt, int l, int r, int ql, int qr){ if(ql <= l && qr >= r){ return sum[rt][0]; } push_down(rt); int res = 0, mid = (l+r) >> 1; if(ql <= mid) res += query(lson, ql, qr); if(qr > mid) res += query(rson, ql, qr); push_up(rt); return res;}int main(){ int T, ca = 1; scanf("%d", &T); while(T--){ int n, q; scanf("%d%d", &n, &q); build(1, 0, n-1); printf("Case %d:\n", ca++); while(q--){ int k, l, r; scanf("%d%d%d", &k, &l, &r); if(k == 0) update(1, 0, n-1, l, r); else printf("%d\n", query(1, 0, n-1, l, r)); } }}
0 0
- [线段树] LightOJ 1135 - Count the Multiples of 3
- lightoj 1135 - Count the Multiples of 3(线段树)
- lightoj 1135 - Count the Multiples of 3
- LightOJ 1135 Count the Multiples of 3(线段树+懒标记)
- LightOJ 1135 Count the Multiples of 3 (Segmengt + 懒惰标记)
- Multiples of 3 线段树+spoj
- SPOJ7299. Multiples of 3
- Count The colors_zoj1610_线段树
- Problem 1:Find the sum of all the multiples of 3 or 5 below 1000.
- Multiples of 3 and 5
- SPOJ 7299 Multiples of 3
- Multiples of 3 and 5
- Multiples of 3 and 5
- Multiples of 3 and 5
- Multiples of 3 and 5
- ZOJ1610 Count the Colors,线段树
- ZOJ 1610Count the Colors//线段树
- zoj 1610 Count the Colors【线段树】
- 初识angularJs
- HDFS工作原理
- JAVAEE学习查询
- 第5课:实战演示JVM三大性能调优参数:-Xms -Xmx -Xss
- 【MFC】:MFC中单选框和复选框的使用教程
- [线段树] LightOJ 1135 - Count the Multiples of 3
- App Widgets
- Myclipse关于不能同时发布项目到几个服务器的尝试
- 11 Eclipse的基本使用&API-常用类(Object类)
- N的阶乘
- 2016年我的坑
- Fragment之间通过EventBus相互传值或调用方法
- 数据结构中双指针的使用
- 转 研究生怎么看论文