zoukankan      html  css  js  c++  java
  • 线段树求逆序对

    • 思路:

      离散化变成一个1-n的数组表示每个数的排名,然后按顺序插入各个数排名,并且查询比它排名大的数的个数。

      这个离散化方法还是比较好的,思维难度和代码难度都比较小。

    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    const int maxn=40005;
    struct Node{
    	int data,rank,index;
    }num[maxn];
    int n,sum[maxn<<2];
    int t,L,R;
    inline bool cmp1(const Node & a,const Node & b)
    {
    	return a.data<b.data;
    }
    inline bool cmp2(const Node & a,const Node & b)
    {
    	return a.index<b.index;
    }
    void add(int now,int l,int r)
    {
    	if(l==r)
    	{
    	    sum[now]++;
    		return ;
    	}
    	int mid=(l+r)>>1;
    	if(t<=mid)add(now<<1,l,mid);
    	else add(now<<1|1,mid+1,r);
        sum[now]=sum[now<<1]+sum[now<<1|1];
        return ;	
    }
    int query(int now,int l,int r)
    {
    	if(L<=l&&r<=R)
    	{
    		return sum[now];
    	}
    	int mid=(l+r)>>1;
    	int ans=0;
    	if(L<=mid)ans+=query(now<<1,l,mid);
    	if(mid<R)ans+=query(now<<1|1,mid+1,r);
    	return ans;
    }
    int main()
    {
    	int n,anss=0;
    	scanf("%d",&n);
    	for(int i=1;i<=n;i++)
    	{
    		scanf("%d",&num[i].data);
    		num[i].index=i;
    	}
    	sort(num+1,num+1+n,cmp1);//离散化开始
    	for(int i=1;i<=n;i++)num[i].rank=i;
    	sort(num+1,num+1+n,cmp2);
        for(int i=1;i<=n;i++)
    	{
    		t=num[i].rank,L=t+1,R=n;
    		add(1,1,n);
    		anss+=query(1,1,n);
    	}		
    	cout<<anss<<endl;
    	return 0;
    }
    
  • 相关阅读:
    230 Kth Smallest Element in a BST 二叉搜索树中第K小的元素
    229 Majority Element II 求众数 II
    bzoj1112: [POI2008]砖块Klo
    bzoj2958: 序列染色&&3269: 序列染色
    bzoj2743: [HEOI2012]采花
    bzoj4247: 挂饰
    bzoj3613: [Heoi2014]南园满地堆轻絮
    bzoj3280: 小R的烦恼
    bzoj1221: [HNOI2001] 软件开发
    bzoj4320: ShangHai2006 Homework
  • 原文地址:https://www.cnblogs.com/Rye-Catcher/p/8617470.html
Copyright © 2011-2022 走看看