8.14 2024第(五)场:信息工程大学
D 区间问题1(树状数组)
链接:https://ac.nowcoder.com/acm/contest/88527/D
来源:牛客网
Alice 有 n 个数,她可以对这 n 个数执行以下两种操作:
1. 将区间 [L,R] 上的所有数加上 d
2. 查询第 x 个数的值
思路
这就是一个树状数组中区间修改,单点查询的模板题。
cqj的博客里有模板树状数组基础知识以及相关习题-CSDN博客
代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define fir(i,a,b) for(int i=a;i<=b;i++)
#define fir_(i,a,b) for(int i=a;i>=b;i--)
#define ALL(x) x.begin(),x.end()
#define lowbit(x) (x&(-x))
#define PII pair<int,int>
#define fi first
#define se second
#define tup tuple<int,int,int>
const int N=1e6+10;
int chafen[N],tree[N];
int n,q;
void update(int x,int d)
{
while(x<=n)
{
tree[x]+=d;
x+=lowbit(x);
}
}
int query(int x)
{int ans=0;
while(x>0)
{
ans+=tree[x];
x-=lowbit(x);
}
return ans;
}
signed main()
{
IOS
cin>>n;
fir(i,1,n)
{
cin>>chafen[i];
update(i,chafen[i]-chafen[i-1]);
}
cin>>q;
while(q--)
{
int f,l,r,d,x;
cin>>f;
if(f==1){
cin>>l>>r>>d;
update(l,d);//左加
update(r+1,-d);//右减
}
else
{
cin>>x;
cout<<query(x)<<'\n';
}
}
}
下面是一道树状数组的练习题
P1908 逆序对 - 洛谷
按照数字从大到小的顺序,将下标放入update更新+1,并查询前缀和,(有一个1,说明一个比他大的,下标还在它前面)
用归并更快,代码是树状数组写的,用vector会T
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define fir(i,a,b) for(int i=a;i<=b;i++)
#define fir_(i,a,b) for(int i=a;i>=b;i--)
#define ALL(x) x.begin(),x.end()
#define lowbit(x) (x&(-x))
#define PII pair<int,int>
#define fi first
#define se second
#define tup tuple<int,int,int>
const int N=5e5+10;
int a[N],tree[N],n,res;
bool cmp(PII a,PII b)
{
if(a.fi!=b.fi) return a.fi<b.fi;
return a.se<b.se;
}
void update(int x,int d)
{
while(x<=n)
{
tree[x]+=d;
x+=lowbit(x);
}
}
int query(int x)
{
int ans=0;
while(x>0)
{
ans+=tree[x];
x-=lowbit(x);
}return ans;
}
signed main()
{
IOS
cin>>n;
PII v[n+1];
fir(i,1,n)
{ int x;
cin>>x;
v[i]={x,i};
}
sort(v,v+n+1,cmp);
fir(i,1,n)
a[i]=v[i].se;
fir_(i,n,1)
{
update(a[i],1);
res+=query(a[i]-1);
}
cout<<res<<'\n';
}
H 区间问题2 (ST表)
区间最值问题,板子题
代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define fir(i,a,b) for(int i=a;i<=b;i++)
const int N=1e6+10;
int n,q,w[N],f[N][21];//2^20>1e6,f[i][k]表示的(i,i+(i<<k)-1)的max
void initialization()
{
fir(j,0,20)
fir(i,1,n-(1<<j)+1)
{
if(!j) f[i][j]=w[i];
else
f[i][j]=max(f[i][j-1],f[i+(1<<j-1)][j-1]); //优先级:*/% +- << >>
}
}
int query(int l,int r)
{
int k=log2(r-l+1);//+1
return max(f[l][k],f[r-(1<<k)+1][k]);
}
signed main()
{
IOS
cin>>n;
fir(i,1,n)
cin>>w[i];
initialization();
cin>>q;
while(q--)
{ int l,r;
cin>>l>>r;
cout<<query(l,r)<<'\n';
}
}