跳到正文

个人记录

HDU-5057 Argestes and Sequence 题解

SunnyYuan约 5 分钟
原文

这是 2025年10月2日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2023年10月14日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

思路

将每个数字拆成很多位并分别进行统计。

非常适合分块题。

单点修改:O(1)O(1)。

区间询问:O(n)O(\sqrt n)。

代码

C++
/*******************************
| Author:  SunnyYuan
| Problem: Argestes and Sequence
| OJ:      Virtual Judge - HDU
| URL:     https://vjudge.net/problem/HDU-5057#author=634579757
| When:    2023-10-14 20:34:27
| 
| Memory:  32 MB
| Time:    2500 ms
*******************************/

#include <bits/stdc++.h>

using namespace std;
using i64 = long long;

const int N = 100010, V = 510;

int n, m, c;
int a[N];
int L[V], R[V], p[N];
int sum[V][16][10];
i64 p10[17];

int query(int l, int r, int x, int v) {
    int p1 = p[l], p2 = p[r];
    if (p1 == p2) {
        int cnt = 0;
        for (int i = l; i <= r; i++) {
            cnt += ((a[i] / p10[x - 1]) % 10) == v;
        }
        return cnt;
    }
    else {
        int cnt = 0;
        for (int i = l; i <= R[p1]; i++) {
            cnt += ((a[i] / p10[x - 1]) % 10) == v;
        }
        for (int i = L[p2]; i <= r; i++) {
            cnt += ((a[i] / p10[x - 1]) % 10) == v;
        }
        for (int i = p1 + 1; i < p2; i++) {
            cnt += sum[i][x][v];
        }
        return cnt;
    }
}

void modify(int u, int x) {
    for (int i = 1; i <= 15; i++) {
        sum[p[u]][i][a[u] % 10]--;
        a[u] /= 10;
    }
    a[u] = x;
    for (int i = 1; i <= 15; i++) {
        sum[p[u]][i][x % 10]++;
        x /= 10;
    }
}

void solve() {
    memset(sum, 0, sizeof(sum));
    memset(L, 0, sizeof(L));
    memset(R, 0, sizeof(R));
    cin >> n >> m;
    c = sqrt(n);
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= c; i++) {
        L[i] = R[i - 1] + 1;
        R[i] = L[i] + c - 1;
    }
    if (R[c] != n) {
        c++;
        L[c] = R[c - 1] + 1;
        R[c] = n;
    }
    for (int j = 1; j <= c; j++) {
        for (int i = L[j]; i <= R[j]; i++) {
            int x = a[i];
            for (int k = 1; k <= 15; k++) {
                sum[j][k][x % 10]++;
                x /= 10;
            }
            p[i] = j;
        }
    }

    char opt;
    int a, b, c, d;

    for (int i = 1; i <= m; i++) {
        cin >> opt;
        if (opt == 'Q') {
            cin >> a >> b >> c >> d;
            cout << query(a, b, c, d) << '\n';
        }
        else {
            cin >> a >> b;
            modify(a, b);
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    p10[0] = 1;
    for (int i = 1; i < 16; i++) p10[i] = p10[i - 1] * 10;

    int T;
    cin >> T;
    while (T--) solve();

    return 0;
}