分治之求数列的逆序数

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

//求逆序数--分治、递归
long QuickSort(vector<int> vecarr1,vector<int> vecarr2)
{
	long iret=0;
	vector<int> vecarr5(vecarr1.size()),vecarr6(vecarr2.size());
	std::copy(vecarr1.begin(),vecarr1.end(),vecarr5.begin());
	std::copy(vecarr2.begin(),vecarr2.end(),vecarr6.begin());
	sort(vecarr5.begin(),vecarr5.end(),greater<int>());
	sort(vecarr6.begin(),vecarr6.end(),greater<int>());
	int i=0,j=0;
	while(i<vecarr5.size()&&j<vecarr6.size())
	{
		if(vecarr5[i]>vecarr6[j])
		{
			iret=iret+vecarr6.size()-j;
			i++;
		}
		else
		{
			j++;
		}
	}
	if(vecarr1.size()>=2)
	{
		int isize1=vecarr1.size()/2,isize2=vecarr1.size()/2;
		if(vecarr1.size()%2==1)
		{
			isize1++;
		}
		vector<int> vecarr3(isize1);
		vector<int> vecarr4(isize2);
		std::copy(vecarr1.begin(),vecarr1.begin()+isize1,vecarr3.begin());
		std::copy(vecarr1.begin()+isize1,vecarr1.end(),vecarr4.begin());
		if(vecarr2.size()>=2)
		{
			isize1=vecarr2.size()/2,isize2=vecarr2.size()/2;
			if(vecarr2.size()%2==1)
			{
				isize1++;
			}
			vector<int> vecarr7(isize1);
			vector<int> vecarr8(isize2);
			std::copy(vecarr2.begin(),vecarr2.begin()+isize1,vecarr7.begin());
			std::copy(vecarr2.begin()+isize1,vecarr2.end(),vecarr8.begin());
			return iret+QuickSort(vecarr3,vecarr4)+QuickSort(vecarr7,vecarr8);
		}
		else
		{
			return iret+QuickSort(vecarr3,vecarr4);
		}
	}
	else
	{
		return iret;
	}
}

int main()
{
	int n=0;
	vector<int> vecarr1;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		int itemp=0;
		cin>>itemp;
		vecarr1.push_back(itemp);
	}
	
	int isize1=vecarr1.size()/2,isize2=vecarr1.size()/2;
	if(vecarr1.size()%2==1)
	{
		isize1++;
	}
	vector<int> vecarr3(isize1);
	vector<int> vecarr4(isize2);
	std::copy(vecarr1.begin(),vecarr1.begin()+isize1,vecarr3.begin());
	std::copy(vecarr1.begin()+isize1,vecarr1.end(),vecarr4.begin());
	cout<<QuickSort(vecarr3,vecarr4)<<endl;
	
	return 0;
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页