Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 50361 | Accepted: 18458 |
Description
Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
Source
离散化+树状数组求逆序对
(离散化用map会超时…)
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<cstring> #include<cstdlib> #include<map> #define F(i,j,n) for(int i=j;i<=n;i++) #define D(i,j,n) for(int i=j;i>=n;i--) #define LL long long #define MAXN 500005 #define pa pair<int,int> using namespace std; int n,b[MAXN],f[MAXN]; LL ans; struct data { int val,pos; }a[MAXN]; int read() { int ret=0,flag=1;char ch=getchar(); while (ch<'0'||ch>'9'){if (ch=='-') flag=-1;ch=getchar();} while (ch>='0'&&ch<='9'){ret=ret*10+ch-'0';ch=getchar();} return ret*flag; } void add(int k) { for(int i=k;i<=n;i+=i&(-i)) f[i]++; } LL getsum(int k) { LL ret=0; for(int i=k;i>0;i-=i&(-i)) ret+=f[i]; return ret; } bool cmp(data x,data y) { return x.val<y.val; } int main() { n=read(); while (n) { memset(f,0,sizeof(f)); ans=0; F(i,1,n) a[i].val=read(),a[i].pos=i; sort(a+1,a+n+1,cmp); F(i,1,n) { if (i>1&&a[i].val==a[i-1].val) b[a[i].pos]=b[a[i-1].pos]; else b[a[i].pos]=i; } D(i,n,1) { if (b[i]>1) ans+=getsum(b[i]-1); add(b[i]); } printf("%lld\n",ans); n=read(); } }