AcWing 第 96 场周赛 T3-4878. 维护数组(树状数组)
https://www.acwing.com/problem/content/4881/
输入样例1:
5 2 2 1 8
1 1 2
1 5 3
1 2 1
2 2
1 4 2
1 3 2
2 1
2 3
输出样例1:
3
6
4
输入样例2:
5 4 10 1 6
1 1 5
1 5 5
1 3 2
1 5 2
2 1
2 2
输出样例2:
7
1
佬儿教的写法
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18,MINN=-MAXN;
const LL N=2e6+10,M=2023;
const LL mod=998244353;
const double PI=3.1415926535;
#define endl '\n'
int n,k,a,b,q;
int tr1[N],tr2[N],d[N];
int lowbit(int x)
{
return x&(-x);
}
void add(int c[],int x,int v)
{
for(int i=x;i<=n;i+=lowbit(i))
{
c[i]+=v;
}
}
int query(int c[],int x)
{
int res=0;
for(int i=x;i>=1;i-=lowbit(i))
{
res+=c[i];
}
return res;
}
int main()
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
int T=1;
//cin>>T;
while(T--)
{
cin>>n>>k>>a>>b>>q;
while(q--)
{
int op;
cin>>op;
if(op==1)
{
int x,y;
cin>>x>>y;
add(tr1,x,min(y,max(0,a-d[x])));
add(tr2,x,min(y,max(0,b-d[x])));
d[x]+=y;
}
else
{
LL p;
cin>>p;
cout<<query(tr2,p-1)+query(tr1,n)-query(tr1,p+k-1)<<endl;
}
}
}
return 0;
}
最高赞写法
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18,MINN=-MAXN;
const LL N=2e6+10,M=2023;
const LL mod=998244353;
const double PI=3.1415926535;
#define endl '\n'
int n,k,a,b,q;
int tr1[N],tr2[N],d[N];
int lowbit(int x)
{
return x&(-x);
}
void add(int c[],int x,int v)
{
for(int i=x;i<=n;i+=lowbit(i))
c[i]+=v;
}
int query(int c[],int x)
{
int res=0;
for(int i=x;i>=1;i-=lowbit(i))
{
res+=c[i];
}
return res;
}
int main()
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
int T=1;
//cin>>T;
while(T--)
{
cin>>n>>k>>a>>b>>q;
while(q--)
{
int op;
cin>>op;
if(op==1)
{
int x,y;
cin>>x>>y;
if(d[x]<a)
{
if(d[x]+y>=a) add(tr1,x,a-d[x]);
else add(tr1,x,y);
}
if(d[x]<b)
{
if(d[x]+y>=b) add(tr2,x,b-d[x]);
else add(tr2,x,y);
}
d[x]+=y;
}
else
{
LL p;
cin>>p;
cout<<query(tr2,p-1)+query(tr1,n)-query(tr1,p+k-1)<<endl;
}
}
}
return 0;
}