zoukankan      html  css  js  c++  java
  • SGU180 Inversions(树状数组求逆序数)

    题目

    思路:先离散化数据然后树状数组搞一下求逆序数。

    离散化的方法https://blog.csdn.net/gokou_ruri/article/details/7723378

    自己对用树状数组求逆序数的理解:输入数据并利用树状数组求出前边比它小和等于它的数据有几个,用输入数据的总的个数减去比它小的数就是比它大的数res,将所有的res加起来就是要求的序列的逆序数。

    如图:

    把所有的res加起来就是答案了

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <queue>
    #include <vector>
    #include <algorithm>
    #define FRE() freopen("in.txt","r",stdin)
    #define INF 0x3f3f3f3f
    
    using namespace std;
    typedef long long ll;
    typedef pair<double,int> P;
    const int maxn = 70000;
    int n;
    int a[maxn],b[maxn],tree[maxn];
    
    int lowbit(int x)
    {
        return x & -x;
    }
    void Add(int x)
    {
        while(x <= n)
        {
            tree[x]++;
            x += lowbit(x);
        }
    }
    int getSum(int x)
    {
        int res = 0;
        while(x>0)
        {
            res += tree[x];
            x -= lowbit(x);
        }
        return res;
    }
    int main()
    {
        scanf("%d",&n);
        for(int i = 0; i < n; i++)
        {
            scanf("%d",&a[i]);
            b[i] = a[i];
        }
        memset(tree,0,sizeof(tree));
        sort(b, b+n);
        int len = unique(b, b+n) - b;
        for(int i = 0; i < n; i++)
        {
            a[i] = lower_bound(b, b + len, a[i]) - b + 1;
        }
        ll sum = 0;
        for(int i = 0; i < n; i++)
        {
            Add(a[i]);
            sum += i + 1 - getSum(a[i]);
        }
        printf("%I64d
    ",sum);
        return 0;
    }
    View Code
  • 相关阅读:
    VBA键码常数
    枚举
    海龟交易法则及头寸
    HQL.TOP
    jquery.cookie
    机械操作产品分析.
    Repeater排序2
    Repeater排序
    json
    LoginStatus注销控件
  • 原文地址:https://www.cnblogs.com/sykline/p/9737781.html
Copyright © 2011-2022 走看看