SGU 180
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
http://acm.sgu.ru/problem.php?contest=0&problem=180
题意是给定n和n个数的数列,每个数<10e9,求出有多少对i,j能满足1<=i<j<=n并且A[i]>A[j]。这道题的题意也就是求数列的逆序数,唯一需要注意的地方是要用long long防止数据爆掉,因为这个WA了3次……其他的基本是用的上一个程序的代码。
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
#include<algorithm>
using namespace std;
#pragma comment(linker,"/STACK:102400000,102400000")
#define pi acos(-1.0)
#define eps 1e-7
#define mod 1000000007
#define INF 0x3f3f3f3f
typedef long long LL;
const int maxn=100005;
int n;
struct node
{
int data;
int pos;
}p[maxn];
LL a[maxn];
LL cnt[maxn];
bool cmp(node a,node b)
{
return a.data<b.data;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int c)
{
while(x<=n)
{
a[x]+=c;
x+=lowbit(x);
}
}
LL sum(int x)
{
LL res=0;
while(x>0)
{
res+=a[x];
x-=lowbit(x);
}
return res;
}
int main(void)
{
int i;
LL ans;
while(scanf("%d",&n)!=EOF)
{
memset(p,0,sizeof(p));
memset(a,0,sizeof(a));
memset(cnt,0,sizeof(cnt));
ans=0;
for(i=1;i<=n;i++)
{
scanf("%d",&p[i].data);
p[i].pos=i;
}
sort(p+1,p+n+1,cmp);
int id=1;
cnt[p[1].pos]=1;
for(i=2;i<=n;i++)
{
if(p[i].data==p[i-1].data)
cnt[p[i].pos]=id;
else
cnt[p[i].pos]=++id;
}
for(i=1;i<=n;i++)
{
update(cnt[i],1);
ans+=i-sum(cnt[i]);
}
printf("%I64d\n",ans);
}
return 0;
}