Find the reverse pair (merge sort application)

Find the reverse pair

Idea: While merging and sorting, if the current element of the current left-ordered sequence is larger than the right when sorting a part, add the number of elements of the current left-ordered sequence to total and output.
Note: the total is large, and long long is required.
Code:

#include<bits/stdc++.h>
using namespace std;
int n,a[100001],c[100001],i;
long long total;
void mergesort(int left,int right){
    
    
	int x=right-left;
	if(!x)return;
	int mid=(left+right)/2;
	mergesort(left,mid);
	int m=mid;
	mid++;
	mergesort(mid,right);
	int cnt=left,l=left;
	while(left<=m&&mid<=right){
    
    
		if(a[left]<=a[mid]){
    
    
			c[cnt]=a[left];
			left++;
		}
		else{
    
    
			c[cnt]=a[mid];
			total+=m-left+1;
			mid++;
		}
		cnt++;
	}
	while(left<=m){
    
    
		c[cnt]=a[left];
		left++;
		cnt++;
	}
	while(mid<=right){
    
    
		c[cnt]=a[mid];
		mid++;
		cnt++;
	}
	for(i=l;i<=right;i++)
		a[i]=c[i];
}
int main(){
    
    
	scanf("%d",&n);
	for(i=1;i<=n;i++)
		scanf("%d",&a[i]);
	mergesort(1,n);
	printf("%lld",total);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_52536621/article/details/113780627