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;
}