时间:2016-05-10 15:33:59 星期二
题目编号:[2016-05-10][51nod][1019 逆序数]
题目大意:求一列数的逆序数
分析:
- 分治
- 把A平均分成B,C两列
- 逆序对(I,j),要么I,j都属于B,要么i,j都属于C,要么I属于B,j属于C,
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
typedef long long ll;
vector<int> A;
ll merge_count(vector<int> & a){
int n = a.size();
if(n <= 1) return 0;
ll cnt = 0;
vector<int> b(a.begin(),a.begin() + n / 2);
vector<int> c(a.begin() + n / 2,a.end());
cnt += merge_count(b);
cnt += merge_count(c);
int ai = 0,bi = 0,ci = 0;
while(ai < n ){
if(bi < b.size() && (ci == c.size() || b[bi] <= c[ci])){
a[ai++] = b[bi++];
}else {
cnt += n / 2 - bi;
a[ai++] = c[ci++];
}
}
return cnt;
}
int main(){
int n,tmp;
scanf("%d",&n);
A.resize(n + 1);
A.clear();
for(int i = 0 ; i < n ; ++i){
scanf("%d",&tmp);
A.push_back(tmp);
}
printf("%lld\n",merge_count(A));
return 0;
}