https://blog.csdn.net/bestsort/article/details/80796531
单点更新+区间查询
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int c[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int y,int n)//更新位置 要更新的数 数组总大小
{
for(int i=x; i<=n; i+=lowbit(i))
{
c[i] += y;
}
}
int getsum(int x)//查询从1~x的和
{
int ans = 0;
for(int i=x; i; i-=lowbit(i))
ans += c[i];
return ans;
}
int main()
{
memset(c,0,sizeof(c));
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
int a;
scanf("%d",&a);
update(i,a,n);
}
printf("%d",getsum(3));
return 0;
}
求逆序对 可以有重复数字
n必须大于等于b数组的最大的数 必要时可离散化
#include <bits/stdc++.h>
using namespace std;
int n,b[30],a[30];
int lowbit(int x)
{
return x&(-x);
}
void update(int p)
{
while(p<=n)
{
a[p] ++;
p+=lowbit(p);
}
}
int getsum(int p)
{
int res = 0;
while(p)
res += a[p],p -= lowbit(p);
return res;
}
int main()
{
scanf("%d",&n);
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(int i=1; i<=n; i++)
{
scanf("%d",&b[i]);
}
for(int i=1; i<=n; i++)
{
int res=0;
update(b[i]);
res = i-getsum(b[i]);//如果换成 res = getsum(b[i])-1; 就是求有多少比他小的数
printf("%d\n",res);
}
return 0;
}
求区间最值 HDU1754
https://blog.csdn.net/qq_41661809/article/details/86667055
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=2e5+5;
int c[maxn],h[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int y,int n)//更新位置 要更新的数 数组总大小
{
while(x<=n)
{
h[x]=c[x];
int lx=lowbit(x);
for(int i=1; i<lx; i<<=1)
{
h[x]=max(h[x],h[x-i]);
}
x+=lowbit(x);
}
}
int getmax(int x,int y)
{
int ans = 0;
while(y>=x)
{
ans=max(ans,c[y]);
y--;
for(; y-lowbit(y)>=x; y-=lowbit(y))
ans=max(h[y],ans);
}
return ans;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
memset(c,0,sizeof(c));
memset(h,0,sizeof(h));
for(int i=1; i<=n; i++)
{
scanf("%d",&c[i]);
update(i,c[i],n);
}
getchar();
for(int i=0; i<m; i++)
{
char ch;
int x,y;
scanf("%c",&ch);
scanf("%d%d",&x,&y);
getchar();
if(ch=='Q')
{
printf("%d\n", getmax(x,y));
}
else
{
c[x]=y;
update(x,y,n);
}
}
}
return 0;
}