其他分享
首页 > 其他分享> > 788. 逆序对的数量

788. 逆序对的数量

作者:互联网

在这里插入图片描述
思路:
利用归并的做法,在归并排序中统计数量
在这里插入图片描述

代码:

# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;

typedef long long LL;

const int N = 100010;
int q[N],tmp[N];
int n;
LL res;

LL merge_sort(int l,int r)
{
    if(l >= r) return 0;
    int mid = l + r >> 1;
    int k = 0,i = l,j = mid + 1;
    
    merge_sort(l,mid);
    merge_sort(mid + 1,r);
  
    while(i <= mid && j <= r)
    {
        if(q[i] <= q[j])
        {
            tmp[k++] = q[i++];
        }
        else
        { 
            res += mid - i + 1;
            tmp[k++] = q[j++];
        }
    }
    while(i <= mid) tmp[k++] = q[i++];
    while(j <= r) tmp[k++] = q[j++];
    
    for(int i = l,j = 0;i <= r;i++,j++) q[i] = tmp[j];
    return res;
}

int main()
{
    scanf("%d",&n);
    for(int i = 0;i < n;i++)
    {
        scanf("%d ",&q[i]);
    }
    
    cout << merge_sort(0,n - 1) << endl;
    
    return 0;
}

标签:tmp,int,LL,788,mid,++,include,数量,逆序
来源: https://blog.csdn.net/qq_45812180/article/details/114758793