Loading

CodeForces-86D Powerful array

Powerful array

问区间出现的各个数字的 次数 值的大小 之和

莫队 模板

我发现用了 inline 在莫队的 add() del() 函数中会快很多

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
#define endl '\n'
typedef long long ll;
const int maxn = 2e5 + 7;
const int maxm = 1e6 + 7;
int pos[maxm];
ll ans = 0, last[maxn], cnt[maxm];
int num[maxn];

inline ll f(ll x)
{
    return cnt[x] * cnt[x] * x;
}

struct node
{
    int l, r, id;
    node(){}
    node(int _l, int _r, int _id){l = _l; r = _r; id = _id;}
}seg[maxn];

bool cmp(const node& a, const node& b)
{
    return pos[a.l] ^ pos[b.l] ? pos[a.l] < pos[b.l] : (pos[a.l] & 1 ? a.r > b.r : a.r < b.r);
}

inline void add(int x)
{
    ans -= f(num[x]);
    cnt[num[x]]++;
    ans += f(num[x]);
}

inline void del(int x)
{
    ans -= f(num[x]);
    cnt[num[x]]--;
    ans += f(num[x]);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, m;
    cin >> n >> m;
    for(int i=1; i<=n; i++) cin >> num[i];
    int t = sqrt(n);
    for(int i=0; i<=n; i++) pos[i] = i / t;
    for(int i=0; i<m; i++)
    {
        int x, y;
        cin >> x >> y;
        seg[i] = node(x, y, i);
    }
    sort(seg, seg + m, cmp);
    int l = 1, r = 0;
    for(int i=0; i<m; i++)
    {
        while(r < seg[i].r) add(++r);
        while(l > seg[i].l) add(--l);
        while(r > seg[i].r) del(r--);
        while(l < seg[i].l) del(l++);
        last[seg[i].id] = ans;
    }
    for(int i=0; i<m; i++)
        cout << last[i] << endl;
    return 0;
}
posted @ 2022-05-25 09:59  dgsvygd  阅读(28)  评论(0)    收藏  举报