#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> #define MAXN 65540 using namespace std; struct node { long long v; int id; bool operator<(const node&p)const {return v<p.v;} }; node a[MAXN+10]; long long c[MAXN+10]; long long b[MAXN+10]; int n; long long lowbit(long long a) { return a&(-a); } long long sum(long long a) { long long s=0; while(a>0) { s+=c[a]; a-=lowbit(a); } return s; } void update(long long a) { while(a<=n+1) { c[a]++; a+=lowbit(a); } } int main(void) { while(scanf("%d",&n)==1) { memset(a,0,sizeof(a)); memset(c,0,sizeof(c)); memset(b,0,sizeof(b)); int i; for(i=1;i<=n;i++) { scanf("%lld",&(a[i].v)); a[i].id=i; } sort(a+1,a+n+1); int pre=-1; int prevalue=0; for(i=1;i<=n;i++) { if(pre!=a[i].v) { pre=a[i].v; a[i].v=++prevalue; } else { a[i].v=prevalue; } } for(i=1;i<=n;i++) { b[a[i].id]=a[i].v; } long long s=0; for(i=n;i>=1;i--) { update(b[i]); s+=sum(b[i]-1); } printf("%I64d\n",s); } return 0; }
原文:http://www.cnblogs.com/767355675hutaishi/p/3849100.html