《算法笔记》13.2小节——专题扩展->树状数组(BIT) 问题 C: Count Inversions
题目描述
给一个数组,算inverted pair的数目
输入
有多组测试样例。每组输入数据占一行,每一行是一个数组,数组之间的元素用空格分开
输出
每组输出结果占一行。对应于每组输入数据的inversions
样例输入
1 2 3
2 1 3
3 2 1
样例输出
0
1
3
分析: 给出一个数组,求逆序数。思路和 A 类似,同样用归并的方法做了。
#include<algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cstdio>
#include <queue>
#include <stack>
#include <ctime>
#include <cmath>
#include <map>
#include <set>
#define INF 0x3fffffff
#define db1(x) cout<<#x<<"="<<(x)<<endl
#define db2(x,y) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<endl
#define db3(x,y,z) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<endl
#define db4(x,y,z,r) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<endl
#define db5(x,y,z,r,w) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<", "<<#w<<"="<<(w)<<endl
using namespace std;long long merge_sum(long long num[],int len)
{if(len==1)return 0;int mid=len/2,l1=0,r1=mid,l2=mid,r2=len,t=0;long long t1=merge_sum(num+l1,mid),t2=merge_sum(num+l2,len-mid),ret=0;int temp[len+5]={0};while(l1<r1||l2<r2){if(l1<r1&&l2<r2){if(num[l1]<num[l2]){temp[t++]=num[l1],l1++;}else temp[t++]=num[l2],l2++,ret+=r1-l1;}else if(l1<r1){temp[t++]=num[l1],l1++;}else if(l2<r2){temp[t++]=num[l2],l2++;}}for(int i=0,j=0;i<len;++i,++j)num[i]=temp[j];return t1+t2+ret;
}char s[500010];
long long num[500010];int main(void)
{#ifdef testfreopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);clock_t start=clock();#endif //testint n;string str;while(getline(cin,str)){n=0;while(str.length()){int pos=str.find(" ");if(pos==string::npos){sscanf(str.c_str(),"%d",&num[n]);break;}elsesscanf(str.substr(0,pos).c_str(),"%d",&num[n]);++n;str.erase(0,pos+1);}n++;long long ans=0;ans=merge_sum(num,n);printf("%lld\n",ans);}#ifdef testclockid_t end=clock();double endtime=(double)(end-start)/CLOCKS_PER_SEC;printf("\n\n\n\n\n");cout<<"Total time:"<<endtime<<"s"<<endl; //s为单位cout<<"Total time:"<<endtime*1000<<"ms"<<endl; //ms为单位#endif //testreturn 0;
}