莫队求助,why TLE
查看原帖
莫队求助,why TLE
726862
zhanglh楼主2024/7/31 20:14
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define ll long long
#define LL __int128
using namespace std;
int n, m, T;
ll a[1000010], c[1000010], ans[1000010], sum;
template <typename T> inline void read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}
struct Range {
    int l, r, id;
    bool operator <(const Range &W)const {
        if (l / T != W.l / T) return l < W.l;
        return r < W.r;
    }
}b[1000010];
inline void add(ll x) {
    sum -= c[x] * c[x] * x;
    c[x] ++ ;
    sum += c[x] * c[x] * x;
}
inline void del(ll x) {
    sum -= c[x] * c[x] * x;
    c[x] -- ;
    sum += c[x] * c[x] * x;
}
int main() {
    read(n), read(m);
    T = sqrt(n);
    for (int i = 1; i <= n; i ++ ) read(a[i]);
    for (int i = 1; i <= m; i ++ ) {
        read(b[i].l), read(b[i].r);
        b[i].id = i;
    }
    sort(b + 1, b + m + 1);
    int L = 1, R = 0;
    for (int i = 1; i <= m; i ++ ) {
        while (L > b[i].l) add(a[ -- L]);
        while (R < b[i].r) add(a[ ++ R]);
        while (L < b[i].l) del(a[L ++ ]);
        while (R > b[i].r) del(a[R -- ]);
        ans[b[i].id] = sum;
    }
    for (int i = 1; i <= m; i ++ ) printf("%lld\n", ans[i]);
    return 0;
}
2024/7/31 20:14
加载中...