SGU 180 Inversions(树状数组求逆序对)

思路:典型的树状数组求逆序对,需要离散化并且数字可能有重复的


#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
const int maxn = 70000+50;
LL c[maxn];
int a[maxn],b[maxn];
vector<int>v;
int getid(int x){return lower_bound(v.begin(),v.end(),x)-v.begin()+1;}
int lowbit(int x){return x&(-x);}
int n;
void update(int i,int num)
{
	while(i<=maxn)
	{
		c[i]+=num;
		i+=lowbit(i);
	}
}
LL query(int x)
{
	LL ans = 0;
	while(x)
	{
		ans+=c[x];
		x-=lowbit(x);
	}
	return ans;
}
int main()
{
    scanf("%d",&n);
	{
		memset(c,0,sizeof(c));
		v.clear();
		for(int i = 1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			b[i]=a[i];
			v.push_back(a[i]);
		}
		sort(b+1,b+1+n);
		for(int i = 1;i<=n;i++)
			a[i]=lower_bound(b+1,b+1+n,a[i])-b;
		//v.push_back(maxn);
		//sort(v.begin(),v.end());
		//v.erase(unique(v.begin(),v.end()),v.end());
		LL ans = 0;
        for(int i = 1;i<=n;i++)
		{
			update(a[i],1);
			ans+=a[i]-query(a[i]-1)-1;
           // ans+=query((maxn))-query((a[i]));
			//update((a[i]),1);
		}
		printf("%I64d\n",ans);
	}	
}

Description

 

180. Inversions
time limit per test: 0.5 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
 
 
Author:Stanislav Angelyuk
Resource:Saratov ST team Spring Contest #1
Date:18.05.2003











Server time: 2013-08-11 22:32:23Online Contester Team © 2002 - 2013. All rights reserved.

 



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值