排列的逆序数(归并排序,树状数组)

题目描述

一个大小为n(2<=n<=1e5)排列中, 对于一个a[i]>a[j] (i

现在给你一个排列, 让你求这个排列有多少个逆序数。

输入

第一行输入n
第二行输入一个排列(1-n)。
输出

输出这个排列的逆序数.
样例输入 Copy

5
4 5 1 3 2

思路:瞎**暴力会超时,那就来归并排序吧。排序是从小到大如果左区间的i大于右区间,那么逆序数为m-i+1.

#include
using namespace std;
long long  COUNT = 0;
int tmp[100005];
void MergeAndCount(int a[], int l, int m, int h)
{
    int i = l;
    int pl = l;
    int ph = m + 1;
    while (pl <= m && ph <= h)
    {
        if (a[pl] <= a[ph]) {
            tmp[i++] = a[pl++];
        }
        else {
            tmp[i++] = a[ph++];
            COUNT += (m - pl + 1);
        }
    }
    while (pl <= m)  tmp[i++] = a[pl++];
    while (ph <= h)  tmp[i++] = a[ph++];
 
    for (int i = l; i <= h; ++i)
        a[i] = tmp[i];
}
 
void MergeSortAndCount(int a[], int l, int h)
{
    if (l < h) {
        int m = (l + h) / 2;
        MergeSortAndCount(a, l, m);
        MergeSortAndCount(a, m + 1, h);
        MergeAndCount(a, l, m, h);
    }
}
 
int main()
{
    int n;
    int a[100005];
    scanf("%d", &n);
    for (int i = 0; i < n; ++i)
        scanf("%d", &a[i]);
    MergeSortAndCount(a, 0, n - 1);
    printf("%lld\n", COUNT);
    return 0;
}

树状数组

#include 
#include 
#include 
#include 
#include
using namespace std;
typedef long long ll;
#define space putchar(' ')
#define enter putchar('\n')
#define ZY set::iterator
const int MOD7 = 1e9 + 7;
const int MOD9 = 1e9 + 9;
const int imax_n = 1e5 + 7;
typedef pair<int,int> PII;
const int inf=0x3f3f3f3f;
//const int mod=1e9+7;
const int N=5e6+10;
const double esp=1e-10;


ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
        write(x / 10);
    putchar('0' + x % 10);
}
int n;
int c[N];
int lowbit(int x)
{
    return x&(-x);
}
void build(int x)
{
    while(x<=n)
    {
        c[x]++;
        x+=lowbit(x);
    }
}
ll getsum(int x)
{
    ll ans=0;
    while(x>0)
    {
        ans+=c[x];
        x-=lowbit(x);
    }
    return ans;
}

int main()
{
    read(n);
    ll res=0;
    for(int i=0;i<n;i++)
    {
        int x;
        read(x);
        res+=getsum(n)-getsum(x);
        build(x);
    }
    write(res);

    return 0;
}

你可能感兴趣的:(多校连萌)