【luogu P1774 最接近神的人_NOI导刊2010提高(02)】 题解

题目链接:https://www.luogu.org/problemnew/show/P1774
归并排序求逆序对。

#include <cstdio>
#define livelove long long
using namespace std;
const int maxn = 600001;
livelove a[maxn], s[maxn], ans = 0, n;//ans用来记录逆序对数量 
void merge_sort(livelove l,livelove r)
{
    if(l == r) return ;
    livelove mid = (l + r)>>1;
    merge_sort(l,mid);
    merge_sort(mid+1,r);//不断划分成两个数列 
    
    livelove 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);
    printf("%lld",ans);
    return 0;
}
posted @ 2018-06-28 18:40  Misaka_Azusa  阅读(140)  评论(0编辑  收藏  举报
Live2D