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

题目描述

一个大小为n(2<=n<=1e5)排列中, 对于一个a[i]>a[j] (i<j), 那么我们称(a[i], a[j])为逆序数。  

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

输入

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

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

5
4 5 1 3 2

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

#include<bits/stdc++.h>
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 <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define space putchar(' ')
#define enter putchar('\n')
#define ZY set<node>::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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值