C++树状数组入门模板和简单应用+二分求逆序对

> #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)//求1至i的和,若需求a至b的和,只需sum(b)-sum(a)+aks(a); 
{
    int s=0;
    while(i>0)
    {
        s+=tree[i];
        i-=lowbit(i);
    }
    return s;
}

int main()
{
	ios::sync_with_stdio(0);cin.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;
}
发布了4 篇原创文章 · 获赞 6 · 访问量 163

猜你喜欢

转载自blog.csdn.net/hrd535523596/article/details/105242886