樹狀數組,是一個用於在近似 O(logn)時間內動態修改以及查詢前綴和的數據結構
該模板有區間修改和區間求和
#include<bits/stdc++.h>
using namespace std;
const int MAX=50005;
int a[MAX],tree[MAX],n;
int lowbit(int x) //找最低位的1
{
return x&-x;
}
void add(int i,int x)//修改數據在i加x
{
while(i<=n)
{
tree[i]+=x;
i+=lowbit(i);
}
}
int sum(int i)
{
int s=0;
while(i>0)
{
s+=tree[i];
i-=lowbit(i);
}
return s;
}
void range_add(int l, int r, int a) //區間修改
{
add(l, a);
add(r + 1, -a);
}
ll range_sum(int l, int r) //區間求和
{
return sum(r) - sum(l - 1);
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
}
例題
樹狀數組入門應用求 逆序對 (求數組右邊比它小的個數和)
因爲卡時間,離散化,用了二分查找下標差,
用tree數組記錄每個數組每次出現的次數。
力扣 315. 計算右側小於當前元素的個數
codeforces 180. Inversions
#include<bits/stdc++.h>
using namespace std;
const int MAX=100010;
const int mod=1e9+7;
#define ll long long
#define _for(i,j,k) for(int i=j;i<k;i++)
#define endl '\n'
#define inf 1<<29
int a[MAX],n,Max;
int tree[MAX];
int lowbit(int x) //找最低位的1
{
return x&-x;
}
void add(int i,int x)//修改數據在i加x
{
while(i<=n)
{
tree[i]+=x;
i+=lowbit(i);
}
}
int sum(int x)//求1至i的和,若需求a至b的和,只需sum(b)-sum(a)+aks(a);
{
int sum = 0;
while (x > 0) {
sum += tree[x];
x -= lowbit(x);
}
return sum;
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
vector<int>ans(n);
for(int i=0;i<n;i++)
{
cin>>a[i];
ans[i]=a[i];
}
sort(ans.begin(),ans.end());
ll cnt=0;
for(int i=n-1;i>=0;i--) //如果換成for(int i=0;i<n;i++),則變成求求數組左邊比它小的個數和
{
int id=lower_bound(ans.begin(),ans.end(),a[i])-ans.begin()+1;
cnt+=sum(id-1);
add(id,1);
}
cout<<cnt;
}