poj2299Ultra-QuickSort(线段树区间求和单点修改)

题意就是让你求一串数列的逆序数

一开始我也思考了一阵,没什么思路 去网上搜了题解,http://www.cnblogs.com/gj-Acit/archive/2013/08/10/3250525.html 他讲的还是挺清楚的。

AC代码:

/* ***********************************************
Author        :yzkAccepted
Created Time  :2016/4/5 20:48:57
TASK		  :ggfly.cpp
LANG          :C++
************************************************ */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <stack>
using namespace std;
typedef __int64 ll;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mem(a) memset(a,0,sizeof(a))
const int maxn=500010;
int tree[maxn<<2],idx[maxn],num[maxn],n;
bool cmp(int a,int b)
{
	return num[a]<num[b];
}
void update(int id,int k,int l,int r,int rt)//单点更新
{
	tree[rt]+=k;
	if(l==r)
		return ;
	int m=l+r>>1;
	if(id<=m)
		update(id,k,lson);
	else
		update(id,k,rson);
}

int query(int L,int R,int l,int r,int rt)//查询
{
	if(L<=l && r<=R) return tree[rt];
	int res=0;
	int m=l+r>>1;
	if(L<=m) res+=query(L,R,lson);
	if(R>m) res+=query(L,R,rson);
	return res;
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int i,j;
	while(~scanf("%d",&n) && n)
	{
		mem(tree);mem(idx);mem(num);
		for(i=1;i<=n;i++)
		{
			scanf("%d",&num[i]);
			update(i,1,1,n,1);
			idx[i]=i;
		}
		sort(idx+1,idx+1+n,cmp);
		ll ans=0;
		for(i=1;i<=n;i++)
		{
			ans+=(query(1,idx[i],1,n,1)-1);//防止越界所以不是 1到idx[i]-1
			update(idx[i],-1,1,n,1);
		}
		cout<<ans<<endl;

	}
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值