问题描述:
(用指针做的线段树,到现在我还是不知道自己为什么没办法用非指针的办法做出来,算是仿照例题,一点点调试出来了吧。又自己做了一遍,完全是凭记忆抄出来的。而且还很模糊,不清楚这样做是否正确。)
解决办法:
1.在建树的时候,uCount要先自增,再赋值给指针。
2.在查询值的时候,是用反复累加返回总和的办法,还有往下走的办法,往左右分支继续往下走。
3.一些很明显的错误,(1)求和的时候,nSum加inc的范围(2)终止条件,s和R匹配就挂掉了,竟然自己看不出来,第二遍的时候还是没有看出来
#include<iostream>
#include<cstdio>
using namespace std;
const int max_n = 100010;
struct CNode
{
int L, R;
long long nSum, inc;
CNode* Left, * Right;
};
int Mid(CNode* root)
{
return (root->L + root->R)/2;
}
CNode tree[2 * max_n];
int nCount = 0;
void BuildTree(CNode* root, int L, int R)
{
root->L = L;
root->R = R;
root->nSum = 0;
root->inc = 0;
if(L == R)
return;
nCount ++;
root->Left = tree + nCount;
nCount ++;
root->Right = tree + nCount;
BuildTree(root->Left, L, (L+R)/2);
BuildTree(root->Right, (L+R)/2 + 1, R);
}
void Insert(CNode* root, int i, int v)
{
if(root->L == i && root->R == i)
{
root->nSum = v;
return;
}
root->nSum += v;
if(i <= Mid(root))
Insert(root->Left, i, v);
else
Insert(root->Right, i, v);
}
void Add(CNode* root, int s, int e, int inc)
{
if(root->L == s && root->R == e)
{
root->inc += inc;
return;
}
root->nSum += (e - s + 1) * inc;
if(e <= Mid(root))
Add(root->Left, s, e, inc);
else if(s > Mid(root))
Add(root->Right, s, e, inc);
else
{
Add(root->Left, s, Mid(root), inc);
Add(root->Right, Mid(root)+1, e, inc);
}
}
long long QuerynSum(CNode* root, int s, int e)
{
if(root->L == s && root->R == e)
{
return root->nSum + (root->R - root->L + 1) * root->inc;
}
root->nSum += (root->R - root->L + 1) * root->inc;
Add(root->Left, root-> L, Mid(root), root->inc);
Add(root->Right, Mid(root)+1, root->R, root->inc);
root->inc = 0;
if(e <= Mid(root))
return QuerynSum(root->Left, s, e);
else if(s > Mid(root))
return QuerynSum(root->Right, s, e);
else
{
return QuerynSum(root->Left, s, Mid(root)) + QuerynSum(root->Right, Mid(root)+1, e);
}
}
int main()
{
int n, q;
scanf("%d%d", &n, &q);
BuildTree(tree, 1, n);
for(int i = 1; i <= n; i++)
{
int v;
scanf("%d", &v);
Insert(tree, i, v);
}
while(q --)
{
char cha[10];
int s, e, inc;
scanf("%s", cha);
if(cha[0] == 'Q')
{
scanf("%d%d", &s, &e);
printf("%lld\n", QuerynSum(tree, s, e));
}
else
{
scanf("%d%d%d", &s, &e, &inc);
Add(tree, s, e, inc);
}
}
}