POJ 2299 Ultra-QuickSort
裸逆序数对~
离散化后,用树状数组统计 “(在a[i]之前加入的) 比a[i]大的数 ” 的个数
贴个模板:
1 #include<map> 2 #include<set> 3 #include<list> 4 #include<cmath> 5 #include<ctime> 6 #include<queue> 7 #include<stack> 8 #include<cctype> 9 #include<cstdio> 10 #include<string> 11 #include<vector> 12 #include<cstdlib> 13 #include<cstring> 14 #include<complex> 15 #include<utility> //pair 16 #include<iostream> 17 #include<algorithm> 18 #define MAXN 500005 19 #define INF 0x3f3f3f3f 20 #define LL long long 21 #define DBL double 22 #define eps 1e-6 23 #define pi acos(-1.0) 24 #define Test() cout<<"Test"<<endl; 25 #define Debug(a) cout<<#a<<" = "<<a<<endl; 26 #define Debug2(a,b) cout<<#a<<" = "<<a<<" , "<<#b<<" = "<<b<<endl; 27 using namespace std; 28 29 int n; 30 int a[MAXN], b[MAXN], c[MAXN]; 31 32 int f(int x){ 33 int l=1, r=n, m; 34 while(l<=r){ 35 m = (l+r)/2; 36 if(x==b[m]) return m; 37 if(x<b[m]) r=m-1; 38 else l=m+1; 39 } 40 return 0; 41 } 42 int lowbit(int x){ 43 return x&(-x); 44 } 45 void add(int p, int x){ 46 for(int i=p; i<=n; i+=lowbit(i)) 47 c[i]+=x; 48 } 49 int sum(int p){ 50 int s=0; 51 for(int i=p; i>0; i-=lowbit(i)) 52 s+=c[i]; 53 return s; 54 } 55 56 int main() 57 { 58 while(cin >> n, n){ 59 for(int i=1; i<=n; i++){ 60 scanf("%d", &a[i]); 61 b[i] = a[i]; 62 } 63 sort(b+1, b+1+n); 64 memset(c, 0, sizeof(c)); 65 LL ans=0; 66 for(int i=1; i<=n; i++){ 67 int rank = f(a[i]); 68 add(rank, 1); 69 ans += (LL)(sum(n)-sum(rank)); 70 } 71 cout << ans << endl; 72 } 73 74 return 0; 75 }