码迷,mamicode.com
首页 > 其他好文 > 详细

求逆序对

时间:2019-07-17 20:26:22      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:bool   tor   printf   color   add   bit   style   merge   can   

归并排序

 1 void merge_sort(int l,int r) {
 2     if (l == r) {
 3         return;
 4     }
 5     int mid = l + r >> 1;
 6     merge_sort(l, mid);
 7     merge_sort(mid + 1, r);
 8     int i = l, j = mid + 1, k = l;
 9     while (i <= mid && j <= r) {
10         if (a[i] <= a[j]) {
11             b[k++] = a[i++];
12         } else {
13             ans+=mid-i+1;
14             b[k++] = a[j++];
15         }
16     }
17     while (i <= mid) {
18         b[k++] = a[i++];
19     }
20     while (j <= mid) {
21         b[k++] = a[j++];
22     }
23     for (int i = l; i <= r; i++) {
24         a[i] = b[i];
25     }
26 }

 

树状数组

 1 struct Node
 2 {
 3     int x,y;
 4     bool operator < (const Node &b) const
 5     {
 6         return x<b.x;
 7     }
 8 }a[N];
 9 int n;
10 int lowbit(int x) {
11     return x & -x;
12 }
13 void add(int x,int d) {
14     for (int i = x; i <= n; i += lowbit(i)) {
15         b[i] += d;
16     }
17 }
18 int sum(int x) {
19     int res = 0;
20     for (int i = x; i; i -= lowbit(i)) {
21         res += b[i];
22     }
23     return res;
24 }
25 
26 int main() {
27     scanf("%d", &n);
28     for (int = 1; i <= n; i++) {
29         scanf("%d", a[i].x);
30         a[i].y = i;
31     }
32     sort(a + 1, a + 1 + n);
33     for (int i = 1; i <= n; i++) {
34         add(a[i].y, 1);
35         ans += i - sum(a[i].y);
36     }
37     printf("%d\n", ans);
38 }

 

求逆序对

标签:bool   tor   printf   color   add   bit   style   merge   can   

原文地址:https://www.cnblogs.com/Accpted/p/11203398.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!