排序:①数值大的先加入树状数组,后加入的发现前面有比自己大的,那么答案+1
②如果数值相同,编号大的优先做(仔细一想还真是)
import java.util.*;
import java.io.*;
//求逆序对个数
public class Main {
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static StreamTokenizer st=new StreamTokenizer(br);
static int nextInt() throws Exception {
st.nextToken();
return (int)st.nval;
}
static PrintWriter pw=new PrintWriter(new OutputStreamWriter(System.out));
static int n;
static node45 a[];
static long tree[];
static int lowbit(int x) {
return x&(-x);
}
static void update(int index,long val) {
for(int i=index;i<=n;i+=lowbit(i)) {
tree[i]+=val;
}
}
static long query(int index) {
long res=0;
for(int i=index;i>=1;i-=lowbit(i)) {
res+=tree[i];
}
return res;
}
public static void main(String []args) throws Exception {
n=nextInt();
a=new node45[n+1];
long ans=0;
int b[]=new int[n+1];
int cnt=1;
for(int i=1;i<=n;i++) {
int c=nextInt();
a[i]=new node45();
a[i].val=c;
a[i].index=i;
}
tree=new long[n+1];
Arrays.sort(a,1,n+1, new Comparator<node45>() {
public int compare(node45 e1,node45 e2) {
if(e1.val==e2.val) {
return e2.index-e1.index;
}
return e2.val-e1.val;
}
});
for(int i=1;i<=n;i++) {
update(a[i].index,1);
ans+=query(a[i].index-1);//不包括自己,前面有多少数,就有多少个逆序对
}
pw.print(ans);
pw.flush();
}
}
class node45{
public int val;
public int index;
public node45(int val, int num) {
this.val = val;
this.index = num;
}
public node45() {
// TODO Auto-generated constructor stub
}
}