• 【逆序对】 模板


    归并排序:

    #include <cstdio>
    #define ll long long
    using namespace std;
    const int maxn = 500001;
    ll a[maxn], s[maxn], ans = 0, n;//ans用来记录逆序对数量 
    void merge_sort(ll l,ll r)
    {
        if(l == r) return ;
        ll mid = (l + r)>>1;
        merge_sort(l,mid);
        merge_sort(mid+1,r);//不断划分成两个数列 
        
        ll i = l, j = mid+1, k =l;
        
        while(i <= mid&&j <= r)
        {
            if(a[i]<=a[j])
            {
                s[k] = a[i],k++,i++;
            }
            
            else 
            {
                s[k] = a[j],k++,j++;
                ans+=mid-i+1;	
            }
        }
        while(i <= mid)
            s[k] = a[i],k++,i++;
        while(j<=r)
            s[k] = a[j],k++,j++;
        for(int i = l; i <= r; i++)
            a[i] = s[i];
    }
    int main()
    {
        scanf("%lld",&n);
        for(int i = 1; i <= n; i++)
        {
            scanf("%lld",&a[i]);	
        } 
        merge_sort(1,n);
        /*for(int i = 1; i <= n; i++)
        {
            printf("%d ",a[i]);
        }*/
        printf("%lld",ans);
        return 0;
    }
    

    BIT:

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #define ll long long
    using namespace std;
    const int maxn = 1e6 + 10;
    ll n, m, A[maxn], B[maxn], ans, L[maxn];
    class BIT{
    	public:
    		ll tree[maxn];
    		void update(ll pos, ll val)
    		{
    			while(pos <= n)
    			{
    				tree[pos] += val;
    				pos += lowbit(pos);
    			}
    		}
    		ll query(ll pos)
    		{
    			ll res = 0;
    			while(pos)
    			{
    				res += tree[pos];
    				pos -= lowbit(pos);
    			}
    			return res;
    		}
    	private:
    		ll lowbit(ll x)
    		{
    			return x & -x;
    		}
    }T;
    int Search(ll x)
    {
    	return lower_bound(B + 1, B + 1 + m, x) - B;
    }
    int main()
    {
    	scanf("%lld",&n);
    	for(int i = 1; i <= n; i++) scanf("%lld",&A[i]), B[i] = A[i];
    	sort(B + 1, B + 1 + n);
    	m = unique(B + 1, B + 1 + n) - B - 1;
    	for(int i = 1; i <= n; i++) A[i] = Search(A[i]);
    	for(int i = 1; i <= n; i++)
    	{
    		T.update(A[i], 1);
    		L[i] = i - T.query(A[i]);
    	}
    	for(int i = 1; i <= n; i++) ans += L[i];
    	printf("%lld",ans);
    	return 0;
    }
    
    
  • 相关阅读:
    java学习day39--SSM整合(方案二)
    java学习day39--SSM整合(方案一)
    @PathVariable注解的作用
    Ajax接收Json数据,调用template模板循环渲染页面的方法
    JS中的DOM与BOM
    关于req.params、req.query、req.body等请求对象
    EJS 高效的 JavaScript 模板引擎
    JavaScript中的变量在内存中的具体存储形式
    JavaScript规定了几种语言类型?
    移动端电商项目总结
  • 原文地址:https://www.cnblogs.com/MisakaAzusa/p/11019610.html
Copyright © 2020-2023  润新知