Time Limit: 250MS | Memory Limit: 4096KB | 64bit IO Format: %I64d & %I64u |
Description
180. Inversions
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
memory limit per test: 4096 KB
input: standard
output: standard
output: standard
There are N integers (1<=N<=65537) A1, A2,.. AN (0<=Ai<=10^9). You need to find amount of such pairs (i, j) that 1<=i<j<=N and A[i]>A[j].
Input
The first line of the input contains the number N. The second line contains N numbers A1...AN.
Output
Write amount of such pairs.
Sample test(s)
Input
5 2 3 1 5 4
Output
3
代码:
#include <stdio.h> #include <algorithm> #include <iostream> using namespace std; #define MAXN 66537 struct node { int x,y; } a[MAXN]; long long sum[MAXN*4]; int b[MAXN]; bool cmp(const node aa,const node bb) { return aa.x<bb.x; } void build(int s,int t,int start) { sum[start]=0; if(s==t) return ; int mid=(s+t)/2; build(s,mid,start*2); build(mid+1,t,start*2+1); } void update(int p,int s,int t,int start) { if(s==t) { sum[start]++; return ; } int mid=(s+t)/2; if(p<=mid) update(p,s,mid,start*2); else update(p,mid+1,t,start*2+1); sum[start]=sum[start*2]+sum[start*2+1]; } long long query(int l,int r,int s,int t,int start) { if(l<=s&&t<=r) return sum[start]; int mid=(s+t)/2; long long ret=0; if(l<=mid) ret+=query(l,r,s,mid,start*2); if(r>mid) ret+=query(l,r,mid+1,t,start*2+1); return ret; } int main() { int n; long long sum1; while(scanf("%d",&n)!=EOF) { build(1,n,1); sum1=0; for(int i=1;i<=n;i++) { scanf("%d",&a[i].x); a[i].y=i; } sort(a+1,a+n+1,cmp); int ans=1; b[a[1].y]=1; for(int i=2;i<=n;i++) { if(a[i-1].x==a[i].x) b[a[i].y]=ans; else { ans++; b[a[i].y]=ans; } } for(int i=1; i<=n; i++) { //cout<<b[i]<<' '; sum1+=query(b[i]+1,n,1,n,1); update(b[i],1,n,1); } printf("%I64d\n",sum1); } return 0; }