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
裸的求逆序对,果断树状数组+离散化。
ps:1.排序的条件写<,不要写<=
2.相同的数,优先级也相同
ps:1.排序的条件写<,不要写<=
2.相同的数,优先级也相同
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 65540;
int N = 0;
struct number
{
int v;
int node;
}A[MAXN] = {0};
int c[MAXN] = {0}, t[MAXN] = {0};
int top = 0;
bool cmp(const number &P, const number &Q) { return P.v < Q.v; }
int find(int cur)
{
int re = 0;
for(; cur; cur -= cur&(-cur)) re += c[cur];
return re;
}
void insert(int cur)
{
for(; cur <= top; cur += cur&(-cur))
c[cur] += 1;
}
int main()
{
scanf("%d", &N);
for(int i = 1; i <= N; ++i)
{
scanf("%d", &A[i].v);
A[i].node = i;
}
sort(A+1, A+N+1, cmp);
A[0].v = -20;
for(int i = 1; i <= N; ++i)
t[A[i].node] = A[i-1].v!=A[i].v?++top:top;
long long ans = 0;
for(int i = 1; i <= N; ++i)
{
insert(t[i]);
ans += (long long)(i-find(t[i]));
}
printf("%I64d", ans);
return 0;
}