【逆序对】 模板

归并排序:

#include <cstdio>
#define ll long long
using namespace std;
const int maxn = 500001;
ll a[maxn], s[maxn], ans = 0, n;//ans用来记录逆序对数量 
void merge_sort(ll l,ll r)
{
    if(l == r) return ;
    ll mid = (l + r)>>1;
    merge_sort(l,mid);
    merge_sort(mid+1,r);//不断划分成两个数列 
    
    ll i = l, j = mid+1, k =l;
    
    while(i <= mid&&j <= r)
    {
        if(a[i]<=a[j])
        {
            s[k] = a[i],k++,i++;
        }
        
        else 
        {
            s[k] = a[j],k++,j++;
            ans+=mid-i+1;	
        }
    }
    while(i <= mid)
        s[k] = a[i],k++,i++;
    while(j<=r)
        s[k] = a[j],k++,j++;
    for(int i = l; i <= r; i++)
        a[i] = s[i];
}
int main()
{
    scanf("%lld",&n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%lld",&a[i]);	
    } 
    merge_sort(1,n);
    /*for(int i = 1; i <= n; i++)
    {
        printf("%d ",a[i]);
    }*/
    printf("%lld",ans);
    return 0;
}

BIT:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
using namespace std;
const int maxn = 1e6 + 10;
ll n, m, A[maxn], B[maxn], ans, L[maxn];
class BIT{
	public:
		ll tree[maxn];
		void update(ll pos, ll val)
		{
			while(pos <= n)
			{
				tree[pos] += val;
				pos += lowbit(pos);
			}
		}
		ll query(ll pos)
		{
			ll res = 0;
			while(pos)
			{
				res += tree[pos];
				pos -= lowbit(pos);
			}
			return res;
		}
	private:
		ll lowbit(ll x)
		{
			return x & -x;
		}
}T;
int Search(ll x)
{
	return lower_bound(B + 1, B + 1 + m, x) - B;
}
int main()
{
	scanf("%lld",&n);
	for(int i = 1; i <= n; i++) scanf("%lld",&A[i]), B[i] = A[i];
	sort(B + 1, B + 1 + n);
	m = unique(B + 1, B + 1 + n) - B - 1;
	for(int i = 1; i <= n; i++) A[i] = Search(A[i]);
	for(int i = 1; i <= n; i++)
	{
		T.update(A[i], 1);
		L[i] = i - T.query(A[i]);
	}
	for(int i = 1; i <= n; i++) ans += L[i];
	printf("%lld",ans);
	return 0;
}

posted @ 2019-06-13 21:26  Misaka_Azusa  阅读(164)  评论(0编辑  收藏
Live2D