Codeforces 749E Inversions After Shuffle Fenwick tree mathematical expectation +

Original link: http://www.cnblogs.com/CJLHY/p/10868251.html

Inversions After Shuffle

If the change is [L, R], then the desired number in reverse order of [L, R] is len * (len - 1) / 2

So our goal became to determine the reverse of the range and in all, this array can be maintained with tree.

#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\n", totinv - tmp1 + tmp2);
    return 0;
}

/*
*/

 

Reproduced in: https: //www.cnblogs.com/CJLHY/p/10868251.html

Guess you like

Origin blog.csdn.net/weixin_30338497/article/details/94875013
Recommended