基础题练习——数组中的逆序对

题目描述:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
输入:
每个测试案例包括两行:
第一行包含一个整数n,表示数组中的元素个数。其中1 <= n <= 10^5。
第二行包含n个整数,每个数组均为int类型。
输出:
对应每个测试案例,输出一个整数,表示数组中的逆序对的总数。
样例输入:
4
7 5 6 4
样例输出:
5
 
  
//有点问题,有组测试用例没通过,时间关系先不管了
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <assert.h>
#include <vector>
using namespace std;
int num[100000];

void computeReverse(int* pStart, int len, int &total)
{
	if(len<=1)
		return;
	int left = len/2;
	int right = len -len/2;//!=num/2
	computeReverse(pStart,left,total);
	computeReverse(pStart+left,right,total);
	//Assume sub problem has solved ,Merge
	int *newArray = new int[len];
	int lpos=left-1,rpos=len-1;
	int dstPos=len-1;
	while(lpos>=0 && rpos>=left)
	{
		if(pStart[lpos]>pStart[rpos])
		{
			total+=(rpos-left+1);
			newArray[dstPos--]=pStart[lpos--];
		}
		else
			newArray[dstPos--]=pStart[rpos--];
	}
	
	while (lpos>=0)
	{
		newArray[dstPos--]=pStart[lpos--];
	}
	while (rpos>=left)
	{
		newArray[dstPos--]=pStart[rpos--];
	}
	assert(dstPos==-1);
	copy(newArray,newArray+len,pStart);
	delete[] newArray;
}

int main()
{
	//freopen("in.txt","r",stdin);
	int n,k;
	while (cin>>n)
	{
		for(int i=0; i<n; i++)
			scanf("%d",num+i);
		int ans=0;
		computeReverse(num,n,ans);
		cout<<ans<<endl;
		
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值