P2709 小B的詢問 莫隊算法初見

傳送門

莫隊算法:處理離線區間查詢,分塊,排序,優雅的暴力。。

代碼主要借鑑b站up主不分解的AgOH。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#define IO                       \
    ios::sync_with_stdio(false); \
    // cin.tie(0);                  \
    // cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 11092019;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
struct Query
{
    int L, R, id;
} q[maxn];
int k, n, m, a[maxn], cnt[maxn]; // cnt 數組記錄次數
int pos[maxn]; // 分塊用
LL ans[maxn], res;
bool cmp(Query a, Query b)
{// 排序規則
    if (pos[a.L] != pos[b.L])
        return pos[a.L] < pos[b.L];
    else
        return a.R < b.R;
}
void add(int p)
{
    cnt[a[p]]++; // 加上貢獻
    res += (cnt[a[p]] * cnt[a[p]]) - (cnt[a[p]] - 1) * (cnt[a[p]] - 1);
}
void sub(int p)
{
    cnt[a[p]]--; // 減去貢獻
    res -= (cnt[a[p]] + 1) * (cnt[a[p]] + 1) - cnt[a[p]] * cnt[a[p]];
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    IO;
    cin >> n >> m >> k;
    int size = sqrt(n);
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i];
        pos[i] = i / size; // 記錄所在塊號
    }
    for (int i = 1; i <= m; i++)
    {
        cin >> q[i].L >> q[i].R;
        q[i].id = i;
    }
    sort(q + 1, q + m + 1, cmp);
    int l = 1, r = 0; // 初始化
    for (int i = 1; i <= m; i++)
    {
        // 指針跳動 得到當前區間
        while (q[i].L < l)
            add(--l);
        while (q[i].R > r)
            add(++r);
        while (q[i].L > l)
            sub(l++);
        while (q[i].R < r)
            sub(r--);
        ans[q[i].id] = res;
    }
    for (int i = 1; i <= m; i++)
        cout << ans[i] << endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章