有n个数,n个操作,每个操作就是在a-b区间上+1;例如:
Sample Input
3 1 2 1 3 2 3
Sample Output
2 3 2
#include<bits/stdc++.h>
using namespace std;
int n;
int a[300010],c[300010],aa[300010];
int lowbit(int x)
{
return x&(-x);
}
void add(int x,int num)//x位置+num
{
while(x<=n)
{
a[x]+=num;
x+=lowbit(x);
}
}
int q(int x)//1->x前缀和
{
int ans=0;
while(x>0)
{
ans+=a[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
int x,y,sum=0;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);
add(x,1);
add(y+1,-1);
}
for(int i=1;i<=n;i++)
printf("%d\n",q(i));
}
return 0;
}
Description
许多天过去了,bigqiu发现一串项链完全不能吸引到所有小姐姐的目光,所以他打算在买一一些鲜花送给窗外的小姐姐,于是他来到了一个花圃,花圃里有各种各样的鲜花。假设不同的鲜花从左到右依次编号(1、2、3、4、5……、n)。bigqiu想知道他如果购买编号a到编号b这个区间的鲜花,他将花费多少钱?为了赚到bigqiu足够多的钱,所以花农可以随意修改编号a到b编号这个区间的鲜花价格。你能帮助bigqiu算出他需要花费多少钱?
Input
每个测试实例第一行为两个整数N,( 1<=N,M<=200000).表示N种个鲜花,M个操作
第二行N个整数,a1,a2,a3,a4……an 代表编号为i的鲜花初始价格。(0<=ai<=1e5)
接下来的M行
每行表示操作的个数,如果第一个数是1,后接3个正整数,a,b,x;代表花农给区间[a,b]内每种鲜花数增加X元, (1<=a<=b<=N)(1<=x<=1e5)
如果是2,后满接2个整数,a,b;代表bigeqiu询问区间[a,b].
Output
每个测试实例输出一行,表示bigeqiu每次询问的价格
Sample Input Copy
1 3 9 4 5 9 8
1 1 2 3
1 1 1 1
2 1 2
Sample Output Copy
11
这个题如果再用上面那个方法就会超时,所以就要用到
a[1]+a[2]+...+a[n]
= (c[1]) + (c[1]+c[2]) + ... + (c[1]+c[2]+...+c[n])
= n*c[1] + (n-1)*c[2] +... +c[n]
= n * (c[1]+c[2]+...+c[n]) - (0*c[1]+1*c[2]+...+(n-1)*c[n])
#include<bits/stdc++.h>
using namespace std;
long long n;
long long a[200010],c[200010],aa[200010],b[200010];
long long lowbit(long long x)
{
return x&(-x);
}
void add(long long x,long long num)//x位置+num
{
while(x<=n)
{
a[x]+=num;
x+=lowbit(x);
}
}
long long q(long long x)//1->x前缀和
{
long long ans=0;
while(x>0)
{
ans+=a[x];
x-=lowbit(x);
}
return ans;
}
void add2(long long x,long long num)
{
while(x<=n)
{
b[x]+=num;
x+=lowbit(x);
}
}
long long q2(long long x)
{
long long ans=0;
while(x>0)
{
ans+=b[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
long long m;
while(~scanf("%lld%lld",&n,&m))
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(long long i=1; i<=n; i++)
{
scanf("%lld",&aa[i]);
c[i]=aa[i]-aa[i-1];
add(i,c[i]);
add2(i,(i-1)*c[i]);
}
while(m--)
{
long long t,a,b,x;
scanf("%lld",&t);
if(t==1)
{
scanf("%lld%lld%lld",&a,&b,&x);
add(a,x);
add(b+1,-x);
add2(a,(a-1)*x);
add2(b+1,b*-x);
}
else
{
long long sum=0;
scanf("%lld%lld",&a,&b);
sum=b*q(b)-(a-1)*q(a-1)+q2(a-1)-q2(b);
printf("%lld\n",sum);
}
}
}
return 0;
}