- 题目描述:
-
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
- 输入:
-
每个测试案例包括两行:第一行包含一个整数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; }