树状数组--求逆序对个数

树状数组求逆序对其实挺简单的

1.将要求的数组离散化
  离散化
    将每一个数的值变为该数在数组中的大小

inline bool cmp(int x, int y)
{
    return a[x] < a[y];
}
for(int i = 1; i <= n; i ++) a[i] = read(), p[i] = i;
sort(p + 1, p + n + 1, cmp); 
for(int i = 1; i <= n; i ++) a[p[i]] = i;

cmp函数,按照该坐标处的数由小到大排序

2.将每个数依次插入树状数组

  1.每次插入查询  0 -> 该数 的值(因为已经离散化成大小,所以a[]的值为 1 -> n)

  2.用 i - 1 - 查询的值  计入ans

    因为比该数小且在改数前的数一定会被查询到

  3.将该数加入树状数组

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;
const int N = 40010;

int a[N], p[N], c[N];
int n;

int read() 
{
    int x = 0, f = 1; char c = getchar();
    while(c < '0' || c > '9') { if(c == '-') f = - 1; c = getchar(); }
    while(c >= '0' && c <= '9') x = x * 10 + c - '0',  c = getchar();
    return x * f;
}

inline bool cmp(int x, int y)
{
    return a[x] < a[y];
}

inline int ask(int x)
{
    int ret = 0;
    while(x)
    {
        ret += c[x];
        x -= x & -x; 
    }
    return ret;
}

void add(int x)
{
    while(x <= n)
    {
        c[x] ++;
        x += x & -x;
    }
    return ;
}

int main()
{
    int ans = 0;
    n = read();
    for(int i = 1; i <= n; i ++) a[i] = read(), p[i] = i;
    sort(p + 1, p + n + 1, cmp); 
    for(int i = 1; i <= n; i ++) a[p[i]] = i;
    for(int i = 1; i <= n; i ++)
    {
        ans += i - 1 - ask(a[i]);
        add(a[i]);
    }
    printf("%d", ans);
    return 0;
}

样例

6
5 4 2 6 3 1
11
posted @ 2017-10-31 06:58  xayata  阅读(400)  评论(0编辑  收藏  举报