zoukankan      html  css  js  c++  java
  • 线段树 区间修改 总结

    #include<fstream>
    #include<string>
    using namespace std;
    ifstream fin("shuliec.in");
    ofstream fout("shuliec.out");
    class Node
    {
    public:
    	long long l;
    	long long r;
    	long long Value;
    	long long Lazy;
    };
    long long d[100001];
    long long N;
    long long ANS=0;
    Node tree[400005];
    void build(long long v,long long l,long long r)//v为结点标号
    {
    	tree[v].l=l;
    	tree[v].r=r;
    	if(l==r)
    	{
    		tree[v].Value=d[r];
    		return ;
    	}
    	long long mid=(l+r)/2;
    	build(v*2,l,mid);
    	build(v*2+1,mid+1,r);
    	tree[v].Value=tree[v*2].Value+tree[v*2+1].Value;
    }
    void update(long long v,long long l,long long r,long long m)
    {
    	tree[v].Value+=(r-l+1)*m;
    	if(tree[v].l==l&&tree[v].r==r)
    	{
    		tree[v].Lazy+=m;
    		return ;
    	}
    	if(tree[v].Lazy!=0)
    	{
    		tree[2*v].Lazy+=tree[v].Lazy;
    		tree[2*v+1].Lazy+=tree[v].Lazy;
    		tree[2*v].Value+=(tree[2*v].r-tree[2*v].l+1)*tree[v].Lazy;
    		tree[2*v+1].Value+=(tree[2*v+1].r-tree[2*v+1].l+1)*tree[v].Lazy;
    		tree[v].Lazy=0;
    	}
    	long long mid=(tree[v].l+tree[v].r)>>1;
    	if(r<=mid)
    		update(v*2,l,r,m);
    	else
    	{
    		if(l>mid)
    			update(2*v+1,l,r,m);
    		else
    		{
    			update(2*v,l,mid,m);
    			update(2*v+1,mid+1,r,m);
    		}
    	}
    }
    void query(long long v,long long l,long long r)
    {
    	if(tree[v].l==l&&tree[v].r==r)
    	{
    		ANS+=tree[v].Value;
    		return ;
    	}
    	if(tree[v].Lazy!=0)
    	{
    		tree[2*v].Lazy+=tree[v].Lazy;
    		tree[2*v+1].Lazy+=tree[v].Lazy;
    		tree[2*v].Value+=(tree[2*v].r-tree[2*v].l+1)*tree[v].Lazy;
    		tree[2*v+1].Value+=(tree[2*v+1].r-tree[2*v+1].l+1)*tree[v].Lazy;
    		tree[v].Lazy=0;
    	}
    	long long mid=(tree[v].l+tree[v].r)/2;
    	if(r<=mid)
    		query(2*v,l,r);
    	else
    	{
    		if(l>mid)
    			query(2*v+1,l,r);
    		else
    		{
    			query(2*v,l,mid);
    			query(2*v+1,mid+1,r);
    		}
    	}
    }
    int main()
    {
    	int i,A,B,C;
    	string temp;
    	fin>>N;
    	for(i=1;i<=N;i++)
    		fin>>d[i];
    	build(1,1,N);
    	fin>>N;
    	for(i=1;i<=N;i++)
    	{
    		fin>>temp;
    		if(temp=="SUM")
    		{
    			fin>>A>>B;
    			query(1,A,B);
    			fout<<ANS<<endl;
    			ANS=0;
    		}
    		if(temp=="ADD")
    		{
    			fin>>A>>B>>C;
    			update(1,A,B,C);
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    break语句和continue语句
    switch注意事项
    运算符优先级
    混合赋值运算符做算数运算时不改变自身数据类型
    arpspoof+ettercap嗅探局域网HTTP/HTTPS账号密码
    linux上chrome、vlc等程序root不能运行的解决办法
    kalilinux、parrotsecos没有声音
    linux相关文章链接
    live kalilinux能保存文件和设置
    渗透测试文章链接
  • 原文地址:https://www.cnblogs.com/jxgapyw/p/4764978.html
Copyright © 2011-2022 走看看