【洛谷1592】【模板】template 线段树 线段树裸题
2015-11-05 09:05
411 查看
模板题,不过好像卡常?
代码:
代码:
[code]#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> using namespace std; const int SIZE=500010; typedef long long LL; struct seg{ int l,r; LL sum,add; }tree[SIZE*4]; void update(int p) { tree[p].sum=tree[p<<1].sum+tree[p<<1|1].sum; } void build(int p,int l,int r) { tree[p].l=l; tree[p].r=r; if(l==r) { tree[p].sum=tree[p].add=0; return ; } int mid=(l+r)>>1; build(p<<1,l,mid); build(p<<1|1,mid+1,r); update(p); } void spread(int p) { if(tree[p].add) { LL d=tree[p].add; tree[p<<1].sum+=d*(tree[p<<1].r-tree[p<<1].l+1); tree[p<<1|1].sum+=d*(tree[p<<1|1].r-tree[p<<1|1].l+1); tree[p<<1].add+=d; tree[p<<1|1].add+=d; tree[p].add=0; } } void change(int p,int l,int r,LL d) { if(l<=tree[p].l&&tree[p].r<=r) { tree[p].add+=d; tree[p].sum+=d*(tree[p].r-tree[p].l+1); return ; } spread(p); int mid=(tree[p].l+tree[p].r)>>1; if(l<=mid) change(p<<1,l,r,d); if(mid<r) change(p<<1|1,l,r,d); update(p); } LL ask(int p,int l,int r) { if(l<=tree[p].l&&tree[p].r<=r) { return tree[p].sum; } spread(p); int mid=(tree[p].l+tree[p].r)>>1; LL ans=0; if(l<=mid) ans+=ask(p<<1,l,r); if(mid<r) ans+=ask(p<<1|1,l,r); return ans; } void scanf(int &n) { n=0; bool flag=0; char a=getchar(); while(a<'0'||a>'9') {if(a=='-') flag=1;a=getchar();} while(a>='0'&&a<='9') n=(n<<3)+(n<<1)+a-'0',a=getchar(); if(flag) n=-n; } void scanf(LL &n) { n=0; bool flag=0; char a=getchar(); while(a<'0'||a>'9') {if(a=='-') flag=1;a=getchar();} while(a>='0'&&a<='9') n=(n<<3)+(n<<1)+a-'0',a=getchar(); if(flag) n=-n; } int main() { int n,m; scanf(n); scanf(m); build(1,1,n); while(m--) { LL s; scanf(s); switch(s) { case 1: int l,r; scanf(l);scanf(r); printf("%lld\n",ask(1,l,r)); break; case 2: int a,b; LL c; scanf(a); scanf(b); scanf(c); change(1,a,b,c); break; } } return 0; }
相关文章推荐
- iOS ---xib自定义cell
- java设计模式之工厂设计模式
- 你真的会玩SQL吗?表表达式,排名函数
- WampServer下修改和重置MySQL密码(转)
- Lowest Common Ancestor of a Binary Search Tree
- JFinal+maven+freemarker入门教程
- 德州扑克程序思路
- 笔记:Delaunay三角剖分(Delaunay Triangulation)相关知识
- Access denied for user 'wuqh'@'localhost' (using password: NO)
- Access denied for user 'wuqh'@'localhost' (using password: NO)
- 调优JVM内存,并解决OutOfMemoryError,StackOverflowError等异常问题
- 图片加载 第三方 KVO
- 每天一个linux命令(35):ln 命令
- 分类解读Spark下的39个机器学习库
- 一个为无阻流量规则分配与端点规则实施而设计的通用最优化框架(四)
- 逆变与协变详解
- CSS padding 属性
- RabbitMQ的安装,配置,监控On Debian8.2
- 取石子
- UILabel ——千变万幻的文字