洛谷3031 高于中位数 树状数组

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cmath>
 4 #include <cstring>
 5 #include <string>
 6 #include <algorithm>
 7 #include <iostream>
 8 #include <iomanip>
 9 #define For(i,j,k) for(int i=j;i<=k;i++)
10 #define Dow(i,j,k) for(int i=j;i>=k;i--)
11 #define LL long long
12 using namespace std ;
13 inline LL read() {
14     LL x = 0 , f = 1 ;
15     char ch = getchar() ;
16     while(ch<'0'||ch>'9') { if(ch=='-') f = -1 ; ch = getchar() ; }
17     while(ch>='0'&&ch<='9') { x = x * 10+ch-48 ; ch = getchar() ; }
18     return x * f ;
19 }
20 inline void write(LL x) {
21     if( x < 0 ) putchar('-') ;
22     if( x > 9 ) write(x/10) ;
23     putchar(x%10+48) ;
24 }
25 inline void writeln(LL x) {
26     write(x) ;
27     putchar('\n') ;
28 }
29 
30 const int N = 100011; 
31 int n,alpha;  
32 struct node{
33     int sum,id,rk;
34 }a[N]; 
35 int tree[N*2]; 
36 LL ans;
37 
38 inline bool cmp_val(node a,node b) {
39     return a.sum < b.sum; 
40 }
41 inline bool cmp_id(node a,node b) {
42     return a.id < b.id; 
43 }
44 inline int lowbit(int x) {
45     return x&(-x); 
46 }
47 inline void add(int x) {
48     for(; x<=n; x+=lowbit(x)) 
49         ++tree[x]; 
50 }
51 inline LL query(int x) {
52     LL res = 0; 
53     for(; x; x-=lowbit(x)) 
54         res+=tree[x]; 
55     return res; 
56 }
57 int main() {
58     n = read(); alpha = read(); 
59     a[1].id = 1; a[1].sum = 0; 
60     For(i, 2, n+1) {
61         int x = read(); a[i].sum = a[i-1].sum; 
62         if( x >= alpha ) a[i].sum++; 
63         else a[i].sum--; 
64         a[i].id = i; 
65     }
66     ++n;
67     sort(a+1, a+n+1, cmp_val); 
68     a[0].sum = a[1].sum-1; 
69     For(i, 1, n) {
70         a[i].rk = a[i-1].rk;
71         if(a[i].sum != a[i-1].sum) 
72             ++a[i].rk; 
73     }
74     sort(a+1, a+n+1, cmp_id); 
75     For(i, 1, n) {
76         ans=ans+query(a[i].rk); 
77         add(a[i].rk); 
78     }
79     printf("%lld\n",ans); 
80     return 0; 
81 }
82 
83 
84 /*
85 
86 
87 洛谷3031 
88 高于中位数 
89 树状数组 
90 
91 
92 */

 

posted @ 2017-12-12 16:00  third2333  阅读(155)  评论(0编辑  收藏  举报