线段树模板一

Description

在这里插入图片描述

Input
在这里插入图片描述

Output
输出包含若干行整数,即为所有操作 2 的结果。
在这里插入图片描述

#include<stdio.h>
#define num 100001
typedef struct node {
	int L, R;
	struct node* left, * right;
	long long sum;
	long long inc;
}Node;

Node tree[2 * num];//这里结构体用的指针所以开两倍叶子节点就行了,如果用直接用数组角标就应该开四倍叶子节点数目
int ncount = 0;//

int Mid(Node* root)
{
	return (root->L + root->R) / 2;
}

void build_tree(Node *root, int L, int R)
{
	root->L = L;
	root->R = R;
	root->sum = 0;
	if (L == R) return;
	//用指针指向左右儿子节点的操作如下,注意count的用法
	ncount++;
	root->left = tree + ncount;
	ncount++;
	root->right = tree + ncount;

	build_tree(root->left, L, (L + R) / 2);
	build_tree(root->right, (L + R) / 2 + 1, R);
}

void insert(Node* root, int i, long long v)//i为即将插入的节点的位置,v即为i这个节点的值
{
	if (root->L == i && root->R == i)
	{
		root->sum = v;
		return;
	}
	root->sum += v;//注意这一步!!
	if (i <= Mid(root)) insert(root->left, i, v);
	else insert(root->right, i, v);
}

void Add(Node* root, int a, int b, long long c)
{
	if (root->L == a && root->R == b)
	{
		root->inc += c;
		return;
	}//向下找到刚好符合我们需要添加的区间,再把区间的inc加上就行了,不用全完递归下去将所有叶子节点都更新,这样就能实现add的O(lgn)复杂度
	root->sum += c * (b - a + 1);
	if (b <= (root->L + root->R) / 2) Add(root->left, a, b, c);
	else if (a >= (root->L + root->R) / 2 + 1) Add(root->right, a, b, c);
	else
	{
		Add(root->left, a, (root->L + root->R) / 2, c);
		Add(root->right, (root->L + root->R) / 2 + 1, b, c);
	}
}

long long querysum(Node* root, int a, int b)
{
	if (root->L == a && root->R == b) return root->sum + (b - a + 1) * root->inc;
	root->sum += (root->R - root->L + 1) * root->inc;
	Add(root->left, root->L, Mid(root), root->inc);//将根结点的inc值向下传
	Add(root->right, Mid(root)+1, root->R, root->inc);//将根结点的inc值向下传
	root->inc = 0;
	if (b <= Mid(root)) return querysum(root->left, a, b);
	else if (a >= Mid(root) + 1) return querysum(root->right, a, b);
	else
	{
		return querysum(root->left, a, Mid(root)) + querysum(root->right, Mid(root) + 1, b);
	}
}

int main()
{
	int i, n, m, op;
	int x, y;
	long long a,z;
	scanf("%d%d", &n, &m);
	build_tree(tree, 1, n);
	for (i = 1; i <= n; i++)
	{
		scanf("%lld", &a);
		insert(tree, i, a);
	}
	for (i = 1; i <= m; i++)
	{
		scanf("%d", &op);
		if (op == 1)
		{
			scanf("%d%d%lld", &x, &y, &z);
			Add(tree, x, y, z);
		}
		else
		{
			scanf("%d%d", &x, &y);
			long long ret = querysum(tree, x, y);
			printf("%lld\n", ret);
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值