sgu180 分类: sgu 2015-03-08 17:55 36人阅读 评论(0) 收藏
其实可以写归并排序求逆序对
但以前写过,就改写了离散化+树状数组
c++离散化真心写得短
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctime>
#include<iostream>
#include<algorithm>
const int MAXN = 100000;
int a[MAXN] = {0} , b[MAXN] = {0}, n, *p;
int sum[MAXN] = {0} , size = 0;
inline int lowbit(const int &x){return x&(-x);}
int count(int x)
{
int ret = 0 ;
while(x > 0)
{
ret += sum[x];
x -= lowbit(x);
}
return ret;
}
void add(int x ,const int &val)
{
while(x <= size)
{
sum[x] += val;
x += lowbit(x);
}
}
int main()
{
long long ans = 0;
#ifndef ONLINE_JUDGE
freopen("sgu180.in","r",stdin);
freopen("sgu180.out","w",stdout);
#endif
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{ scanf("%d",&a[i]); b[i] = a[i];}
std::sort(b + 1, b +n +1);
p = std::unique(b + 1, b + n +1);
size = p - (b + 1) ;
for(int i = 1; i <= n; i++)
a[i] = std::lower_bound(b + 1, p , a[i]) - b;
for(int i = 1; i <= n; i++)
{
ans += (count(size) - count(a[i]));
add(a[i] , 1);
}
printf("%I64d",ans);
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。