(分治)逆序数计数

 1 #include<bits/stdc++.h>
 2 #include <iostream>
 3 using namespace std;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 vector <int> A;
 7 int n,tem;
 8 ll merge_count(vector <int> &a)
 9 {
10     int m=a.size();
11     if(m<=1)
12         return 0;
13 
14     ll cnt=0;
15     vector <int> b(a.begin(),a.begin()+m/2);
16     vector <int> c(a.begin()+m/2,a.end());
17     cnt+=merge_count(b);
18     cnt+=merge_count(c);
19     int ai=0,bi=0,ci=0;
20     while(ai<m)
21     {
22         if(bi<b.size()&&(ci==c.size()||b[bi]<=c[ci]))
23         {
24             a[ai++]=b[bi++];
25         }
26         else
27         {
28             cnt+=m/2-bi;
29             a[ai++]=c[ci++];
30         }
31     }
32     return cnt;
33 
34 }
35 int main()
36 {
37     scanf("%d",&n);
38     for(int i=0;i<n;i++)
39         {
40             scanf("%d",&tem);
41             A.push_back(tem);
42         }
43     printf("%lld\n",merge_count(A));
44     return 0;
45 }

 

posted @ 2017-01-16 13:06  perplex  阅读(326)  评论(0编辑  收藏  举报