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
几个点,一个是离散化数据,再有是用stable_sort(),或者改下cmp因为相同数据的相对位置不能变,模板题。
#include <bits/stdc++.h>
using namespace std;
struct node{
int id;
int v;
}no[70000];
int a[70000];
int bit[70000];
int n;
void print(){
cout<<endl;
for(int i=1;i<=n;i++){
cout<<bit[i]<<" ";
}
cout<<endl;
}
int sum(int i){
int s=0;
while(i>0){
s+=bit[i];
i-=i&-i;
}
return s;
}
void add(int i,int x){
while(i<=n){
bit[i]+=x;
i+=i&-i;
}
}
bool cmp(node x,node y){
return x.v<y.v;
}
void solve(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&no[i].v);
no[i].id=i;
}
stable_sort(no+1,no+1+n,cmp);
for(int i=1;i<=n;i++){
a[no[i].id]=i;
}
long long ans=0;
for(int i=1;i<=n;i++){
ans+=i-1-sum(a[i]);
add(a[i],1);
//print();
}
printf("%lld",ans);
return;
}
int main(){
solve();
return 0;
}