Codeforces 1167F Scalar Queries 树状数组

原文链接: http://www.cnblogs.com/CJLHY/p/10874005.html

Scalar Queries

昨天没打好像亏疯了, 好像都是sb题啊。

我们先考虑单个区间[L, R],  对于[L, R]中的一个数 x , 我们只需要只要有多少个数字排序之后排到它前面去了就好。

那么整体来说对于 x , 只有比 x 小的数字对 x 有贡献, 我们只要计算出所有比它小的数字, 在所有包含 x 的线段中排到 x 前面的次数。

这个可以用数组数组维护。   

#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 = 5e5 + 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 {
    int a[N];
    void modify(int x, int v) {
        for(int i = x; i < N; i += i & -i) add(a[i], v);
    }
    int sum(int x) {
        LL ans = 0;
        for(int i = x; i; i -= i & -i) add(ans, a[i]);
        return ans;
    }
    int query(int L, int R) {
        if(L > R) return 0;
        return (sum(R) - sum(L - 1) + mod) % mod;
    }
} bit[2];

int n, a[N], id[N];
LL cnt[N];

bool cmp(int x, int y) {
    return a[x] < a[y];
}

int main() {
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) scanf("%d", &a[i]), id[i] = i;
    sort(id + 1, id + 1 + n, cmp);
    int ans = 0;
    for(int i = 1; i <= n; i++) {
        int x = id[i];
        LL cnt = 0;
        add(cnt, 1LL * bit[0].query(1, x - 1) * (n - x + 1) % mod);
        add(cnt, 1LL * bit[1].query(x + 1, n) * x % mod);
        add(cnt, 1LL * x * (n - x + 1) % mod);
        add(ans, cnt * a[x] % mod);
        bit[0].modify(x, x);
        bit[1].modify(x, n - x + 1);
    }
    printf("%d\n", ans);
    return 0;
}

/*
*/

转载于:https://www.cnblogs.com/CJLHY/p/10874005.html

猜你喜欢

转载自blog.csdn.net/weixin_30338497/article/details/94875015