a287困難分塊、區塊排序與整數平均門檻
TOI 2026/05 潛力組:超越平均
同時維護區間總和與大於平均的人數,讓單點修改和區間查詢都不必掃描整段。
解題思路
A、B 各自建立原陣列,初始 B[i]=500−A[i],之後只修改指令指定的一欄。將每欄分成長度約 √N 的區塊,每塊保存總和與排序副本;更新時從排序副本刪除舊值、插入新值並修改總和。因此每個區塊始終精確表示目前那一欄的資料。
查詢先以整塊總和及兩端零散元素算出 S,令長度為 L。整數 x 嚴格高於平均等價於 x>floor(S/L),即使 S 為負也成立。第二次走訪區間,完整區塊用 upper_bound 找出大於門檻的元素數,零散位置直接比較。兩次走訪使用同一個固定門檻,不能改用各區塊自己的平均。C++ 對負數除法需補成向下取整。
Step-by-step animation
公開範例:兩欄獨立維護(以完整區間呈現)
步驟 1 / 3
查詢 A
A 的總和為 1000,四人的平均為 250。
100
200
300
400
- 門檻
- 250
- 答案
- 2
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
struct Blocks {
int n, b;
vector<long long> a, sum;
vector<vector<long long>> sorted;
Blocks(vector<long long> v)
: n(v.size()), b((int)sqrt(n) + 1), a(v), sum((n + b - 1) / b), sorted(sum.size()) {
for (int i = 0; i < n; i++) {
sum[i / b] += a[i];
sorted[i / b].push_back(a[i]);
}
for (auto &s : sorted)
sort(s.begin(), s.end());
}
void add(int i, long long p) {
auto &s = sorted[i / b];
s.erase(lower_bound(s.begin(), s.end(), a[i]));
a[i] += p;
sum[i / b] += p;
s.insert(upper_bound(s.begin(), s.end(), a[i]), a[i]);
}
int query(int l, int r) {
long long total = 0;
for (int i = l; i <= r;) {
if (i % b == 0 && i + b - 1 <= r) {
total += sum[i / b];
i += b;
} else
total += a[i++];
}
long long len = r - l + 1, t = total / len;
if (total < 0 && total % len)
--t;
int ans = 0;
for (int i = l; i <= r;) {
if (i % b == 0 && i + b - 1 <= r) {
auto &s = sorted[i / b];
ans += s.end() - upper_bound(s.begin(), s.end(), t);
i += b;
} else
ans += a[i++] > t;
}
return ans;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, q;
cin >> n >> q;
vector<long long> a(n), b(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
b[i] = 500 - a[i];
}
Blocks A(a), B(b);
while (q--) {
int op, x, y;
char f;
cin >> op >> x >> y >> f;
Blocks &v = (f == 'A' ? A : B);
if (op == 1)
v.add(x - 1, y);
else
cout << v.query(x - 1, y - 1) << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。