SGU 180

SGU 180


180. Inversions
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值