zoukankan      html  css  js  c++  java
  • Codeforces 749E Inversions After Shuffle 树状数组 + 数学期望

    Inversions After Shuffle

    如果改变的是[L, R], 那么[L, R]内的逆序对数的期望为 len * (len - 1) / 2

    所以我们的目标变成了, 求出所有区间内的逆序对之和, 这个用树状数组就能维护了。

    #include<bits/stdc++.h>
    #define LL long long
    #define LD long double
    #define ull unsigned long long
    #define fi first
    #define se second
    #define mk make_pair
    #define PLL pair<LL, LL>
    #define PLI pair<LL, int>
    #define PII pair<int, int>
    #define SZ(x) ((int)x.size())
    #define ALL(x) (x).begin(), (x).end()
    #define fio ios::sync_with_stdio(false); cin.tie(0);
    
    using namespace std;
    
    const int N = 1e5 + 7;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int mod = 1e9 + 7;
    const double eps = 1e-8;
    const double PI = acos(-1);
    
    template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;}
    template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;}
    template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;}
    template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;}
    
    struct Bit {
        LL a[N];
        void init() {
            memset(a, 0, sizeof(a));
        }
        void modify(int x, int v) {
            for(int i = x; i < N; i += i & -i) a[i] += v;
        }
        LL sum(int x) {
            LL ans = 0;
            for(int i = x; i; i -= i & -i) ans += a[i];
            return ans;
        }
        LL query(int L, int R) {
            if(L > R) return 0;
            return sum(R) - sum(L - 1);
        }
    };
    
    int n, a[N];
    Bit bit;
    LL totinv;
    
    int main() {
        scanf("%d", &n);
        for(int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            totinv += bit.query(a[i] + 1, n);
            bit.modify(a[i], 1);
        }
        bit.init();
        LL ret1 = 0, ret2 = 0;
        for(LL i = 1; i <= n; i++) {
            ret1 += (n - i + 1) * bit.query(a[i] + 1, n);
            bit.modify(a[i], i);
        }
        double tmp1 = 2.0 * ret1 / n / (n + 1);
        for(LL i = 1; i <= n; i++) {
            LL cnt = n - i + 1;
            ret2 += i * (i - 1) / 2 * cnt;
        }
        double tmp2 = 1.0 * ret2 / n / (n + 1);
        printf("%.12f
    ", totinv - tmp1 + tmp2);
        return 0;
    }
    
    /*
    */
  • 相关阅读:
    Linux进程间通信分类 以及 pipe的原理实现
    单链表的快速排序
    再谈二分查找
    数据库范式
    二分查找法浅析
    C# Observer设计模式
    C# 交错数组浅析
    C语言初学 数学中带根号的复杂计算问题
    C语言初学 计算三角形面积问题
    C语言初学 简单定义圆的面积计算问题
  • 原文地址:https://www.cnblogs.com/CJLHY/p/10868251.html
Copyright © 2011-2022 走看看