P1908 逆序对(树状数组) 讲解
-
题目:P1908 逆序对
-
题意:求 数列中 且 的数量.
-
解题思路:
-
离散化:
将原始数组映射到 的连续整数,解决数值过大导致的树状数组空间浪费问题。
-
逆序遍历统计:
从后向前遍历数组,每次操作:
查询前缀和:统计已插入元素中小于当前元素的数量。
插入当前元素:将当前元素位置标记为已出现。
-
树状数组操作:
单点更新:插入元素时,将对应位置值 。
前缀和查询:查询当前元素左侧已插入元素的数量。
-
其他:
需要倒序排序。
时间复杂度:
- 参考代码:
//#pragma GCC optimize(3)
#include<cstdio>
#include<algorithm>
#define int long long//数据范围大,记得开 long long
using namespace std;
inline int read()//快读
{
int x=0,f=1;
char s;
s=getchar();
while(s<48||s>57)
{
if(s=='-')f=-f;
s=getchar();
}
while(s>47&&s<58)
{
x=(x<<3)+(x<<1)+(s-48);
s=getchar();
}
return x*f;
}
const int N=5e5+1;
struct Node
{
int val;
int pos;
}a[N];//保存数列 a 的数值和位置
bool cmp(Node x,Node y)//逆序对:倒序排序
{
if(x.val==y.val)return x.pos>y.pos;
return x.val>y.val;
}
int n;
int ans;//答案
int sum[N];//树状数组
int lowbit(int x)//获取整数二进制表示中最低位的1及其后所有0组成的数值
{
return x&-x;
}
void update(int x,int k)//更新
{
for(;x<=n;x+=lowbit(x))sum[x]+=k;
}
int query(int x)//查询
{
int res=0;
for(;x;x-=lowbit(x))res+=sum[x];
return res;
}
signed main()
{
n=read();
int i;
for(i=1;i<=n;++i)
{
a[i].val=read();//数值
a[i].pos=i;//下标
}
sort(a+1,a+1+n,cmp);//离散化
for(i=1;i<=n;++i)
{
ans+=query(a[i].pos-1);//查询
update(a[i].pos,1);//更新
}
printf("%lld",ans);
return 0;
}