P13976 数列分块入门 1 題解

· · 题解

題目描述

處理一個長度為 n 的數列,支持兩種操作:

若使用暴力,時間複雜度會逹到 O(n^2),無法通過 subtask 2,因此考慮使用分塊。

甚麼是分塊?

分块是將數組列分成若干個大小相近的塊,平衡時間複雜度。

如何分塊?

  1. 將長度為 n 的數組分成 m 個塊,每個塊的大小為 \frac{n}{m}。
  2. 對每個塊,使用一個「懶標記」(類似線段樹)記錄該塊內所有元素需要累加的值,以避免每次更新時都遍歷塊內所有元素。

分塊的最佳大小

塊的大小是分塊算法的關鍵,直接影響時間複雜度。下面將分析為甚麼選擇 \sqrt{n} 作為塊大小最好:

設塊的大小為 s,則總塊數為 m = \lceil\frac{n}{s}\rceil。

對於區間操作,可以分成下列兩部分:

即單次操作的總時間複雜度為 O(s + m) = O(s + \frac{n}{s})。

設 f(x) = s + \frac{n}{s}。
根據均值不等式 f(x) = s + \frac{n}{s} \ge 2 \sqrt{s \times \frac{n}{s}} = 2 \sqrt{n} ,當且僅當 s = \sqrt{n} 時等號成立。

因此,當塊大小為 \sqrt{n} 時,單次操作的時間複雜度最佳,為 O(\sqrt{n})。對於 n 次操作,總時間複雜度為 O(n\sqrt{n})。

代碼實現

#include <iostream>
#include <cmath>
using namespace std;

const int MAXN = 300005;
long long a[MAXN];
int belong[MAXN];
long long add[1000];
int size;
int n;

int main() {
    cin >> n;
    size = sqrt(n);
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= n; i++) belong[i] = (i - 1) / size;

    for (int i = 0; i < n; i++) {
        int opt, l, r;
        long long c;
        cin >> opt >> l >> r >> c;
        if (opt == 0) {
            int L = belong[l];
            int R = belong[r];
            if (L == R) {
                for (int j = l; j <= r; j++) {
                    a[j] += c;
                }
            } else {
                int end_L = (L + 1) * size;
                for (int j = l; j <= end_L; j++) a[j] += c;
                for (int j = L + 1; j < R; j++) add[j] += c;

                int start_R = R * size + 1;
                for (int j = start_R; j <= r; j++) a[j] += c;
            }
        } else {
            cout << a[r] + add[belong[r]] << "\n";
        }
    }
    return 0;
}