萌新刚学OI,莫队RE#8求助
查看原帖
萌新刚学OI,莫队RE#8求助
610557
shinzanmonoszm 妹妹楼主2022/10/8 12:56
#include <bits/stdc++.h>
using namespace std;
const int sz = 2e5 + 10;
using ll = long long;
struct query {
    int l, r, id, block;
    bool operator<(const query &a) {
        if (block != a.block) return block < a.block;
        if (block & 1) return r < a.r;
        return r > a.r;
    }
} que[sz];
ll ans[sz], t[sz], cnt, li[5 * sz];
void add(int x) {
    cnt += (2 * t[li[x]] + 1) * li[x];
    ++t[li[x]];
}
void del(int x) {
    cnt += (1 - 2 * t[li[x]]) * li[x];
    --t[li[x]];
}
int main() {
    ios::sync_with_stdio(false);
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> li[i];
    for (int i = 1; i <= m; i++) {
        int l, r;
        cin >> l >> r;
        int b = (l - 1) / sqrt(n) + 1;
        que[i] = query{l, r, i, b};
    }
    sort(que + 1, que + m + 1);
    int le = 1, re = 0;
    for (int i = 1; i <= m; i++) {
        int l = que[i].l, r = que[i].r;
        while (le < l) del(le++);
        while (le > l) add(--le);
        while (re < r) add(++re);
        while (re > r) del(re--);
        ans[que[i].id] = cnt;
    }
    for (int i = 1; i <= m; i++) cout << ans[i] << endl;
    return 0;
}
2022/10/8 12:56
加载中...