树状数组求逆序对

来源:互联网 发布:温度测试仪软件 编辑:程序博客网 时间:2024/05/16 11:28

题目>>http://codevs.cn/problem/1688/

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int MAXN = 1e6 + 5;long long tree[MAXN],n,a,ans = 0;void add(long long x){    while(x <= 1e5)    {        tree[x] ++;        x += (x & (-x));    }}long long sum(long long x){    long long ans = 0;    while(x)    {        ans += tree[x];        x -= (x & (-x));    }    return ans;}int main(){    scanf("%lld",&n);    for(long long i = 1;i <= n;i ++)    {        scanf("%lld",&a);        add(a);//以树状数组为桶并记录个数。         ans += i - sum(a);//容斥,比这个数大的数 = 总的数的个数 - 比他小的。     }    printf("%lld",ans);}
原创粉丝点击