【归并排序求逆序对个数】【树状数组求逆序对个数】
2017-09-03 16:48
453 查看
【AC】
树状数组求逆序对个数
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<string> 5 #include<cmath> 6 #include<algorithm> 7 using namespace std; 8 typedef long long ll; 9 const int maxn=5e5+2; 10 11 int n; 12 ll ans; 13 struct node 14 { 15 int x; 16 int pos; 17 }a[maxn]; 18 int tree[maxn]; 19 int r[maxn]; 20 bool cmp(node nd1,node nd2) 21 { 22 return nd1.x<nd2.x; 23 } 24 int lowbit(int x) 25 { 26 return x&-x; 27 } 28 void add(int k,int x) 29 { 30 while(k<=n) 31 { 32 tree[k]+=x; 33 k+=lowbit(k); 34 } 35 } 36 ll query(int k) 37 { 38 ll ans=0; 39 while(k) 40 { 41 ans+=tree[k]; 42 k-=lowbit(k); 43 } 44 return ans; 45 } 46 int main() 47 { 48 while(scanf("%d",&n)&&n) 49 { 50 for(int i=1;i<=n;i++) 51 { 52 scanf("%d",&a[i].x); 53 a[i].pos=i; 54 } 55 sort(a+1,a+n+1,cmp); 56 for(int i=1;i<=n;i++) 57 { 58 r[a[i].pos]=i; 59 } 60 memset(tree,0,sizeof(tree)); 61 ans=0; 62 for(int i=1;i<=n;i++) 63 { 64 add(r[i],1); 65 ans+=i-query(r[i]); 66 } 67 cout<<ans<<endl; 68 } 69 return 0; 70 }
树状数组求逆序对个数
相关文章推荐
- hdu 1394 Minimum Inversion Number (裸树状数组 求逆序数 && 归并排序求逆序数)
- 51 nod 1019 逆序数【归并排序||树状数组】
- Ultra-QuickSort---poj2299 (归并排序.逆序数.树状数组.离散化)
- poj2299 Ultra-QuickSort&&NYOJ117 求逆序数 (树状数组求逆序对数+离散化)+(归并排序)
- 归并排序,树状数组 两种方法求逆序对
- POJ 2299 Ultra-QuickSort(树状数组+离散化 或 归并排序求逆序)
- hdoj 1394 Minimum Inversion Number 【线段树 or 线段树lazy or 树状数组 or 归并排序】【逆序对】
- 求逆序对模板题(完善模板:树状数组或归并排序)
- NYOJ 117 求逆序数 【树状数组】或【归并排序】
- Ultra-QuickSort (poj 2299 归并排序 || 树状数组 求逆序对)
- [洛谷P1908] 逆序对|归并排序|树状数组
- 归并排序,树状数组 两种方法求逆序对
- 逆序对的两种算法【树状数组 / 归并排序】
- [hdu]1394 Minimum Inversion Number -- 暴力求逆序、树状数组求逆序、线段树求逆序、归并排序求逆序
- poj 2299 求逆序对 树状数组 归并排序
- E - Inversion-归并排序求逆序对/树状数组求逆序对
- 【算法】逆序对问题的四种解法(归并排序,BST,树状数组,线段树)及变形
- nyoj 117 求逆序数【线段树 树状数组 归并排序】
- 二分·归并排序与树状数组之逆序对 hiho1141
- hiho一下 第三十九周 #1141 : 二分·归并排序之逆序对 【归并排序----树状数组】