codevs 1080 线段树练习

时间:2021-11-14 12:41:32

链接:http://codevs.cn/problem/1080/

先用树状数组水一发,再用线段树水一发

树状数组代码:84ms

 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<vector>
#include<queue>
#include<iterator>
#include<vector>
#include<set>
#define dinf 0x3f3f3f3f
typedef long long ll;
const int Max=(<<)+;
using namespace std; #define SIZE 1000005 int c[SIZE],a[SIZE]; int Lowbit(int x)
{
return x&(-x);
} int Sum(int x)
{
int sum=;
while(x>)
{
sum+=c[x];
x-=Lowbit(x);
}
return sum;
} void Update(int i,int x)
{
while(i<=SIZE)//要把所有的与i相关的c数组中的值全部更新,不然会出错
{
c[i]+=x;
i+=Lowbit(i);
}
} int main()
{
int n,m;
while(~scanf("%d",&n))
{
memset(a,,sizeof(a));
memset(c,,sizeof(c)); for(int i=;i<=n;i++)
{
scanf("%d",&a[i]);
Update(i,a[i]);
}
scanf("%d",&m);
int op,node,num;
for(int i=;i<=m;i++)
{
scanf("%d %d %d",&op,&node,&num);
if(op==)
Update(node,num);
else if(op==)
{
printf("%d\n",Sum(num)-Sum(node-));
}
}
}
return ;
}

线段树代码:48ms

 #include<cstdio>
using namespace std;
struct RE
{
int sum,l,r;
}tree[];
int a[];
void build(int node,int l,int r)
{
int mid=(l+r)>>;
tree[node].l=l;
tree[node].r=r;
if (l==r)
{
tree[node].sum=a[l];
return;
}
build(*node,l,mid);
build(*node+,mid+,r);
tree[node].sum+=tree[*node].sum+tree[*node+].sum;
}
void updata(int node,int a,int b)
{
int mid=(tree[node].l+tree[node].r)>>;
if (mid==tree[node].l&&mid==tree[node].r)
{
tree[node].sum+=b;
return;
}
if (a<=mid)
updata(*node,a,b);
else
updata(*node+,a,b);
tree[node].sum+=b;
}
int query(int node,int l,int r)
{
int mid=(tree[node].l+tree[node].r)>>;
if (tree[node].l==l&&tree[node].r==r)
return tree[node].sum;
if (l>mid)
return query(*node+,l,r);
if (r<=mid)
return query(*node,l,r);
return query(*node,l,mid)+query(*node+,mid+,r);
}
int main()
{
int n,m;
scanf("%d",&n);
int i,j;
for (i=;i<=n;i++)
scanf("%d",&a[i]);
build(,,n);
scanf("%d",&m);
int sign,a,b;
for (i=;i<=m;i++)
{
scanf("%d%d%d",&sign,&a,&b);
if (sign==) updata(,a,b);
else printf("%d\n",query(,a,b));
}
return ;
}