Time Limit Exceeded 求逆序对数。

/**
题目:Time Limit Exceeded
链接:https://oj.ejq.me/problem/28
题意:求逆序对数。
思路:树状数组求逆序对数。维护前面有多少个<=当前数的数的个数。
*/
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn = 1e6+10;
const int mod = 1e9+7;
ll c[maxn];
int flag[maxn];
int n;
int a[maxn];
int lowbit(int t)
{
    return t&(-t);
}
ll getSum(int pos)
{
    ll sum = 0;
    while(pos>0){
        sum += c[pos];
        pos -= lowbit(pos);
    }
    return sum;
}
void update(int pos,int add)
{
    while(pos<=n){
        c[pos]+=add;
        pos += lowbit(pos);
    }
}
int main()
{
    while(scanf("%d",&n)==1)
    {
        memset(flag, 0, sizeof flag);
        for(int i = 1; i <= n; i++){
            scanf("%d",&a[i]);
            flag[a[i]] = 1;
        }
        int index = 1;///树状数组从1开始。
        for(int i = 0; i <= 1000000; i++){
            if(flag[i]){
                flag[i] = index++;
            }
        }
        memset(c, 0, sizeof c);
        ll ans = 0;
        for(int i = 1; i <= n; i++){
            ans += i-1-getSum(flag[a[i]]);
            update(flag[a[i]],1);
        }
        printf("%lld
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiaochaoqun/p/6696503.html