P1908 reverse order pair (Luogu)

Original title portal

Insert picture description here
Insert picture description here
Idea: This question is really a pit, the direct violence method has to time out, add a merge sort template and pay attention to how to find the number of reverse pairs, because the two paragraphs are in order, so find one in the previous paragraph than the one in the latter When it is large, all the numbers after the previous paragraph are larger than it, and the statistical number is m-i+1. This is the key point of this problem. Then the algorithm is divide and conquer + merge sort, which involves recursion the process of.

Code reference

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 500005;
int n,a[MAXN],temp[MAXN];
long long ans=0;
//归并排序
void merge(int l,int r)
{
    
    
    if(l==r)
        return;
    int m=(l+r)/2;
    merge(l,m);
    merge(m+1,r);
    int i=l,j=m+1,k=l;
    while(i<=m && j<=r)
    {
    
    
        if(a[i]>a[j])
        {
    
    
            temp[k]=a[j];
            k++;
            j++;
            ans+=(m-i+1);//统计逆序对的数量
        }
        else
        {
    
    
            temp[k]=a[i];
            k++;
            i++;
        }
    }
    while(i<=m)
    {
    
    
        temp[k]=a[i];
        k++;
        i++;
    }
    while(j<=r)
    {
    
    
        temp[k]=a[j];
        k++;
        j++;
    }
    for(i=l;i<=r;i++)
        a[i]=temp[i];
}
int main()
{
    
    
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    merge(1,n);
    cout<<ans;
    return 0;
}

Guess you like

Origin blog.csdn.net/Bertil/article/details/106818042