http://acm.hdu.edu.cn/showproblem.php?pid=3743
离散化+树状数组
View Code
1 #include <cstdio>
2 #include <cstring>
3 #include <algorithm>
4 using namespace std;
5
6 const int N=1000100,maxn=1000000;
7 int val[N],a[N],c[N];
8 int lowbit(int x)
9 {
10 return x&(-x);
11 }
12 int bfind(int x,int l,int r)
13 {
14 while(l<r)
15 {
16 int m=(l+r)>>1;
17 if(x==val[m]) return m;
18 else if(x<val[m]) r=m;
19 else l=m+1;
20 }
21 return l;
22 }
23 int main()
24 {
25 int n;
26 while (~scanf("%d",&n))
27 {
28 for(int i=1;i<=n;i++)
29 {
30 scanf("%d",&a[i]);
31 val[i]=a[i];
32 }
33 sort(val+1,val+n+1);
34 memset(c,0,sizeof(c));
35 __int64 ans=0;
36 for(int i=1;i<=n;i++)
37 {
38 int x=bfind(a[i],1,n);
39 __int64 cnt=0;
40 for(int j=x-1;j>0;j-=lowbit(j)) cnt+=c[j];
41 ans+=i-cnt-1;
42 for(int j=x;j<=maxn;j+=lowbit(j)) c[j]++;
43 }
44 printf("%I64d\n",ans);
45 }
46 return 0;
47 }