审查 AI 写的 BigInt 树状数组:动态权重、零平台与累计位置查找
让 AI 写一个树状数组,最容易得到的答案通常很短:用最低有效位跳转,查询时不断减,更新时不断加。然而,真正需要审查的不是循环是否眼熟,而是它在维护什么事实。一个累计权重系统可能每个桶都很小,总数却已经超过 JavaScript 的安全整数边界;也可能减去一笔权重后出现负数,求和仍然看似正常,按累计位置定位却悄悄失效。
本文围绕固定长度、非负整数权重构造一套可执行的审查方法。我们保留动态单点增减、单点赋值、前缀和、区间和以及累计秩定位,不涉及滑动窗口,也不依赖数据库。目标不是让模型多写几行注释,而是让每项承诺都对应明确反例、独立参考模型和确定输出。

先把接口约定写给审查者
元素索引统一为零基 Number 整数,合法范围是零到长度减一。prefix(end) 返回半开区间 [0,end) 的权重,range(start,end) 返回 [start,end),所以空区间必须得到 0n,end 可以等于长度。权重、增量、累计和与查找目标全部使用 BigInt;接口不自动把 Number、字符串或对象转换成 BigInt。负增量可以合法,负权重始终不合法。
lowerBound(target) 的目标必须是正 BigInt。它返回最小元素索引 i,使 prefix(i+1) 大于等于 target;找不到时返回 length。注意返回的是元素索引,不是前缀右端点,调用方若要后者必须加一。我们拒绝零目标,避免把空前缀、首个零权重桶和首个正权重桶混成一个含糊的默认行为。空数组和全零数组对任意正目标都返回长度哨兵。
下面恰好九个程序各自完整,均可另存为对应的 .mjs 文件,直接用 node --unhandled-rejections=strict 文件名.mjs 执行,不安装依赖,也不导入其他示例。实测环境是 Node.js v24.19.0。后八段有意重复同一份类定义,保证单独复制即可运行;阅读时可把注意力放在类后的断言。每段之后给出精确标准输出,断言失败则退出,不把错误藏在展示文字里。
一、先证明精度风险,再决定输入边界
累计值的正确性不能靠最后再调用 BigInt 来补救。一个十进制整数一旦先经过不安全的 Number 表示,丢失的信息不会因转换而回来。第一段同时展示相邻整数碰撞和精确计算,再用非常窄的十进制入口拒绝空白、前导零、小数、指数和负号。这个入口只适用于外部权重文本,核心类仍只接受 BigInt,避免每次更新都重演解析规则。末尾换行也在反例内:正则的结束锚点可能匹配最后换行之前,所以入口先检查首尾空白。
这里的规范依据是 ECMAScript 的安全整数边界以及 数值类型约定。BigInt 适合精确整数运算,不意味着任意输入长度都没有成本。实际服务还应在入口限制字符串长度和业务额度;把百万位数字直接交给解析器,也会消耗时间与内存。
示例文件:01_integer_gate.mjs
import assert from "node:assert/strict";
function parseWeight(text) {
if (typeof text !== "string" || text !== text.trim() ||
!/^(0|[1-9][0-9]*)$/.test(text)) {
throw new TypeError("canonical nonnegative decimal required");
}
return BigInt(text);
}
const rounded = Number("9007199254740993");
assert.equal(rounded, Number("9007199254740992"));
assert.equal(BigInt(rounded), 9007199254740992n);
const exact = parseWeight("9007199254740993") + 1n;
assert.equal(exact, 9007199254740994n);
assert.throws(() => 1n + 1, TypeError);
for (const bad of [1, "01", "-1", "1.5", "1e3", " 2", "2 ", "1\n", "1\r\n", ""]) {
assert.throws(() => parseWeight(bad), TypeError);
}
console.log("unsafe collision:", rounded === Number("9007199254740992"));
console.log("exact total:", String(exact));
console.log("input gate: PASS");精确标准输出:
unsafe collision: true exact total: 9007199254740994 input gate: PASS
二、把一基内部结构藏在零基接口后面
Fenwick 节点 tree[i] 保存内部一基区间 i-lowbit(i)+1 到 i 的和,对应外部半开区间 [i-lowbit(i),i)。查询前缀时不断清除末尾的一个置位,将目标前缀拆成互不重叠的片段;更新元素时则沿包含它的节点向上走。构造函数按顺序把已完成的小块送给父块,因此只遍历一遍数组。
类把原始权重和树节点都设为私有字段,初始值按固定长度逐项读取、校验并复制,不调用输入数组自定义的迭代器;稀疏数组中的空洞也会被当成非法值。示例设置一百万个元素的实现上限,这是教学实现的资源策略,不是语言的数组最大长度。Number 位运算会经过三十二位转换,不能因为权重改成 BigInt 就认定索引也天然安全;这个明确上限让所有 lowbit 操作留在正的三十二位索引范围内。查找步长使用乘二和整除二,避免带符号移位的额外边界。
读第二段时建议先手算 prefix(2) 和 range(1,3)。前者包含前两个元素,后者只包含索引一和二。如果 AI 给出的例子恰好全是相同权重,索引错误很容易被掩盖;本例特意放入一个零和几个不同数值。
示例文件:02_index_contract.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
const tree = new Fenwick([2n, 0n, 5n, 1n]);
const sums = Array.from({ length: 5 }, (_, end) => tree.prefix(end));
assert.deepEqual(sums, [0n, 2n, 2n, 7n, 8n]);
assert.equal(tree.range(1, 3), 5n);
assert.equal(tree.range(4, 4), 0n);
assert.equal(tree.total(), 8n);
assert.throws(() => tree.prefix(-1), RangeError);
assert.throws(() => tree.prefix(1.5), RangeError);
assert.throws(() => tree.prefix(1n), RangeError);
assert.throws(() => tree.range(3, 2), RangeError);
assert.throws(() => new Fenwick([1n, -1n]), RangeError);
assert.throws(() => new Fenwick([1]), TypeError);
assert.throws(() => new Fenwick(Array(1)), TypeError);
assert.throws(() => new Fenwick(Array(1_000_001)), RangeError);
const custom = [2n, 4n];
custom[Symbol.iterator] = function* () { yield -1n; };
assert.deepEqual(new Fenwick(custom).snapshot(), [2n, 4n]);
console.log("prefixes:", sums.map(String).join(","));
console.log("range [1,3):", String(tree.range(1, 3)));
console.log("index contract: PASS");精确标准输出:
prefixes: 0,2,2,7,8 range [1,3): 5 index contract: PASS
三、动态更新先保护所有权,再保护不变量
add 接受增量,set 接受目标权重。二者不能混用:set 需要先减去当前位置的旧值,才能把正确差值传播到树节点。我们额外保存一份原始权重,这样就可以直接判断更新后是否为负,也避免每次赋值都用两次前缀查询反推出旧值。
外部数组与 snapshot 返回值都不能成为绕过校验的后门。第三段先修改构造输入,再修改导出的副本,检查实例仍保持自己的状态。类的固定长度也是契约的一部分:增加新桶、删除旧桶、调整桶顺序都需要重新构建或设计另一套接口,不能偷偷对内部数组 push 后继续期待已有树节点成立。这里的负增量合法,因为它没有让最终权重小于零。
示例文件:03_dynamic_updates.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
const input = [4n, 0n, 3n, 2n];
const tree = new Fenwick(input);
input[0] = 999n;
assert.equal(tree.prefix(1), 4n);
tree.add(1, 5n);
tree.add(0, -2n);
tree.set(3, 1n);
assert.deepEqual(tree.snapshot(), [2n, 5n, 3n, 1n]);
assert.equal(tree.total(), 11n);
assert.equal(tree.range(1, 3), 8n);
const copy = tree.snapshot();
copy[2] = 0n;
assert.equal(tree.range(2, 3), 3n);
tree.add(2, 0n);
assert.equal(tree.total(), 11n);
console.log("weights:", tree.snapshot().map(String).join(","));
console.log("total:", String(tree.total()));
console.log("copy isolation: PASS");精确标准输出:
weights: 2,5,3,1 total: 11 copy isolation: PASS
四、抛出异常之后,还要检查全部可见状态
常见的 AI 错误是先减掉原始权重或一部分树节点,再发现结果为负而抛错。调用方看到了异常,通常会认为操作没有发生;如果实现只回滚其中一个数组,下一次查询便会依赖不一致状态。因此 add 在任何写入前先验证索引、增量类型和新权重,并暂存所有受影响节点的新值,准备完成之后才提交。
第四段并不满足于检查 throws。它为每次非法调用收集权重快照、所有前缀、所有合法区间、全部相关累计位置和总数,逐项比较拒绝前后是否相等。最后再执行一次合法减法,确认实例还能继续工作。本文的原子性指同步接口因参数或业务规则拒绝时不留下部分修改,不承诺进程崩溃、内存耗尽、共享内存并发或跨多次调用的事务隔离。
预计算暂存会额外使用对数级临时空间,这是一项明示的工程取舍。生产代码如果删除暂存步骤,应重新论证提交阶段没有可能被业务输入触发的异常,而不是因为测试暂时没报错就把失败语义改掉。
示例文件:04_atomic_rejection.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
const tree = new Fenwick([2n, 0n, 4n]);
function visibleState() {
const prefixes = [];
const ranges = [];
for (let r = 0; r <= tree.length; r++) {
prefixes.push(tree.prefix(r));
for (let l = 0; l <= r; l++) ranges.push(tree.range(l, r));
}
const locations = [];
for (let t = 1n; t <= tree.total() + 1n; t++) {
locations.push(tree.lowerBound(t));
}
return [tree.snapshot(), prefixes, ranges, locations, tree.total()];
}
const badCalls = [
[() => tree.add(0, -3n), RangeError],
[() => tree.add(-1, 1n), RangeError],
[() => tree.add(3, 1n), RangeError],
[() => tree.add(1, 1), TypeError],
[() => tree.add(1.5, 1n), RangeError],
[() => tree.set(2, -1n), RangeError],
[() => tree.set(2, 1), TypeError],
[() => tree.prefix(4), RangeError],
[() => tree.range(2, 1), RangeError],
[() => tree.lowerBound(0n), RangeError],
[() => tree.lowerBound(1), TypeError],
[() => tree.lowerBound(-1n), RangeError]
];
for (const [call, ErrorType] of badCalls) {
const before = visibleState();
assert.throws(call, ErrorType);
assert.deepEqual(visibleState(), before);
}
tree.add(2, -1n);
assert.equal(tree.total(), 5n);
console.log("rejected calls:", badCalls.length);
console.log("all rejected states unchanged: true");
console.log("next valid total:", String(tree.total()));精确标准输出:
rejected calls: 12 all rejected states unchanged: true next valid total: 5
五、零权重平台决定比较符号的方向
非负权重保证前缀和单调不减,但不保证严格递增。连续零权重会制造平台:目标恰好等于平台高度时,正确答案是第一次达到目标的那个有权重元素,不是平台最右端。因此二进制提升只在候选累计和严格小于 target 时接受整块前进;把小于改成小于等于,会跨过本应返回的元素。
查找始终维护一个尚未到达目标的前缀:sum 等于 prefix(index),且 sum 小于目标。step 从不超过长度的最大二次幂开始,逐次缩半;若再加入当前块仍未达到目标,就吸收该块。结束后 index 正好是可跳过元素的数量,它也就是零基答案。若所有元素仍未达到目标,数量等于 length,自然得到哨兵。第五段在目标命中累计边界、落在下一桶内部以及超过总和三种情况下同时检查结果。
这也解释了为什么不能允许负权重。树状数组本身可以用来求带符号数的和,但这里的按秩查找依赖单调性。若业务确实需要负权重,就应拆分能力边界或改用适合该问题的数据结构,不能只删除构造函数中的负值检查。
示例文件:05_zero_plateaus.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
const tree = new Fenwick([0n, 2n, 0n, 0n, 3n, 0n]);
const targets = [1n, 2n, 3n, 5n, 6n];
const indices = targets.map(t => tree.lowerBound(t));
assert.deepEqual(indices, [1, 1, 4, 4, 6]);
for (let target = 1n; target <= tree.total(); target++) {
const i = tree.lowerBound(target);
assert.ok(tree.prefix(i) < target);
assert.ok(tree.prefix(i + 1) >= target);
assert.ok(tree.range(i, i + 1) > 0n);
}
assert.equal(tree.lowerBound(tree.total() + 1n), tree.length);
console.log("targets:", targets.map(String).join(","));
console.log("indices:", indices.join(","));
console.log("zero plateaus: PASS");精确标准输出:
targets: 1,2,3,5,6 indices: 1,1,4,4,6 zero plateaus: PASS
六、空树与非二次幂长度不能留给运气
小规模边界通常比大规模随机数据更能暴露错误。空树没有任何合法元素索引,却仍有合法的前缀边界零;单元素树的查找答案只可能是零或一;全零树的总数为零,却不应该把任意正目标映射到第一个桶。第六段分别验证这些语义,再把一个全零树激活并清空,确认历史状态不会影响下一次查询。
长度五的例子让唯一正权重位于最后一格,专门排除只在二次幂长度上正确的搜索写法。超大权重则用十的四十次方构造,确保比较过程没有悄悄退回 Number。返回值仍是小的 Number 索引;数字域的分工按职责决定,不能为了看起来统一而把数组下标也全部改成 BigInt。
示例文件:06_degenerate_shapes.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
const empty = new Fenwick([]);
assert.equal(empty.prefix(0), 0n);
assert.equal(empty.range(0, 0), 0n);
assert.equal(empty.total(), 0n);
assert.equal(empty.lowerBound(1n), 0);
assert.throws(() => empty.add(0, 1n), RangeError);
const zeros = new Fenwick([0n, 0n, 0n]);
assert.equal(zeros.lowerBound(1n), 3);
console.log("empty sentinel:", empty.lowerBound(1n));
console.log("all-zero sentinel:", zeros.lowerBound(1n));
zeros.set(1, 9n);
assert.equal(zeros.lowerBound(9n), 1);
zeros.set(1, 0n);
assert.equal(zeros.lowerBound(1n), 3);
const huge = 10n ** 40n;
const one = new Fenwick([huge]);
assert.equal(one.lowerBound(huge), 0);
assert.equal(one.lowerBound(huge + 1n), 1);
const five = new Fenwick([0n, 0n, 0n, 0n, 7n]);
assert.equal(five.lowerBound(7n), 4);
assert.equal(five.lowerBound(8n), 5);
console.log("singleton and n=5: PASS");精确标准输出:
empty sentinel: 0 all-zero sentinel: 3 singleton and n=5: PASS
七、参考模型不要复制被测算法
第七段用普通数组当作事实来源:前缀逐个累加,区间用两个参考前缀相减,查找从左到右扫描。参考模型里没有 lowbit,也没有二进制提升;如果两边恰好复制了同一个错误,它们的相等就没有证明力。固定种子只负责生成可复现操作序列,不用作安全随机数,也不据此宣称任何抽样分布质量。
八种长度各运行两百轮,覆盖赋值、合法增减、归零和应被拒绝的超额扣减。每一轮都检查全部前缀与全部合法区间,再检查累计边界和边界后一单位的定位结果。大数会穿插在普通小数之间,避免只验证平均情况。随机测试补足长序列状态变化,却无法保证遍历所有输入,所以还需要下一段小空间穷举。
示例文件:07_reference_sequences.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
let seed = 0x12345678;
function random() {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return seed;
}
function linearLowerBound(a, target) {
let sum = 0n;
for (let i = 0; i < a.length; i++) {
sum += a[i];
if (sum >= target) return i;
}
return a.length;
}
function check(tree, a) {
assert.deepEqual(tree.snapshot(), a);
const prefix = [0n];
for (const w of a) prefix.push(prefix.at(-1) + w);
for (let r = 0; r <= a.length; r++) {
assert.equal(tree.prefix(r), prefix[r]);
for (let l = 0; l <= r; l++) {
assert.equal(tree.range(l, r), prefix[r] - prefix[l]);
}
}
const targets = new Set([1n, prefix.at(-1) + 1n]);
for (const p of prefix) {
if (p > 0n) targets.add(p);
targets.add(p + 1n);
}
for (const target of targets) {
assert.equal(tree.lowerBound(target), linearLowerBound(a, target));
}
}
let rounds = 0;
for (const n of [0, 1, 2, 3, 5, 8, 9, 17]) {
const a = Array(n).fill(0n);
const tree = new Fenwick(a);
for (let step = 0; step < 200; step++) {
if (n > 0) {
const i = random() % n;
if (step % 11 === 0) {
assert.throws(() => tree.add(i, -a[i] - 1n), RangeError);
} else {
const next = step % 31 === 0 ? 10n ** 30n : BigInt(random() % 9);
if (step % 2 === 0) tree.set(i, next);
else tree.add(i, next - a[i]);
a[i] = next;
}
}
check(tree, a);
rounds++;
}
}
assert.equal(rounds, 1600);
console.log("model rounds:", rounds);
console.log("model comparison: PASS");精确标准输出:
model rounds: 1600 model comparison: PASS
八、用穷举寻找随机测试漏掉的平台组合
第八段枚举长度零到五、每项取零一二的全部三百六十四个数组。每个位置再尝试从负三到正三的增量,共一万一千四百八十七次更新;合法操作与非法操作都要在操作后重新对照参考数组。查找目标覆盖一到总和加一,因此每个平台边缘、每个可用累计位置和越界哨兵都会出现。
这不是对任意规模的数学证明,它只是把最容易混淆的形状压缩成可以穷尽的有限集合。它与前面的循环不变量说明互相补充:证明解释为什么算法成立,穷举帮助发现代码是否忠实实现了证明。审查 AI 代码时,这种组合比要求模型再口头确认一次正确性更有价值。
示例文件:08_exhaustive_states.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
function check(tree, a) {
let sum = 0n;
assert.equal(tree.prefix(0), 0n);
for (let i = 0; i < a.length; i++) {
sum += a[i];
assert.equal(tree.prefix(i + 1), sum);
}
assert.equal(tree.total(), sum);
for (let l = 0; l <= a.length; l++) {
for (let r = l; r <= a.length; r++) {
assert.equal(tree.range(l, r), a.slice(l, r).reduce((s, w) => s + w, 0n));
}
}
for (let target = 1n; target <= sum + 1n; target++) {
let prefix = 0n;
const expected = a.findIndex(w => (prefix += w) >= target);
assert.equal(tree.lowerBound(target), expected < 0 ? a.length : expected);
}
}
let arrays = 0;
let attempts = 0;
for (let n = 0; n <= 5; n++) {
for (let mask = 0; mask < 3 ** n; mask++) {
let rest = mask;
const a = Array.from({ length: n }, () => {
const w = BigInt(rest % 3);
rest = Math.floor(rest / 3);
return w;
});
check(new Fenwick(a), a);
arrays++;
for (let i = 0; i < n; i++) {
for (let d = -3n; d <= 3n; d++) {
const tree = new Fenwick(a);
const model = a.slice();
if (model[i] + d < 0n) {
assert.throws(() => tree.add(i, d), RangeError);
} else {
tree.add(i, d);
model[i] += d;
}
assert.deepEqual(tree.snapshot(), model);
check(tree, model);
attempts++;
}
}
}
}
assert.equal(arrays, 364);
assert.equal(attempts, 11487);
console.log("exhaustive arrays:", arrays);
console.log("update attempts:", attempts);
console.log("exhaustive comparison: PASS");精确标准输出:
exhaustive arrays: 364 update attempts: 11487 exhaustive comparison: PASS
九、业务适配层再检查一次累计位置的起点
最后一段把外部零基票号转换成内部正目标:票号 t 对应 lowerBound(t+1)。alpha、paused、beta、gamma 是四个固定桶名,权重表示各桶占用的整数位置数量;paused 初始权重为零,因此不会分到任何位置。随后打开 paused、清空 alpha,之前非常大的总量变成七,定位依然遵守同一套约定。
适配层先拒绝负票号、等于总数的票号、Number 票号和空集合票号,再访问返回索引,防止把 length 哨兵直接拿去索引标签数组。这个例子只验证已给定整数位置的归属,不实现随机抽样;不能把 Math.random 乘以超大总数再取整,便宣称获得了无偏、精确的 BigInt 随机选择。
上线前还要明确总量单位、输入字长上限、长度上限与数据恢复格式。如果要通过 JSON 保存权重,应该由边界层定义十进制字符串协议并在恢复时校验,不要让存储格式反过来偷偷放宽核心接口。若桶的身份或排序发生变化,标签与权重必须作为同一版本一起重建,否则算术完全正确也可能把结果关联到错误业务对象。
示例文件:09_ticket_adapter.mjs
import assert from "node:assert/strict";
class Fenwick {
#weights;
#tree;
constructor(weights) {
if (!Array.isArray(weights)) throw new TypeError("weights must be an array");
const length = weights.length;
if (!Number.isSafeInteger(length) || length < 0 || length > 1_000_000) {
throw new RangeError("length limit");
}
this.#weights = Array(length);
for (let i = 0; i < length; i++) {
const value = weights[i];
this.#weight(value);
this.#weights[i] = value;
}
this.#tree = Array(this.length + 1).fill(0n);
for (let i = 1; i <= this.length; i++) {
this.#tree[i] += this.#weights[i - 1];
const parent = i + (i & -i);
if (parent <= this.length) this.#tree[parent] += this.#tree[i];
}
}
get length() { return this.#weights.length; }
#index(i, end = false) {
const limit = this.length - (end ? 0 : 1);
if (!Number.isSafeInteger(i) || i < 0 || i > limit) {
throw new RangeError("index out of range");
}
}
#weight(value) {
if (typeof value !== "bigint") throw new TypeError("weight must be bigint");
if (value < 0n) throw new RangeError("negative weight");
}
snapshot() { return this.#weights.slice(); }
prefix(end) {
this.#index(end, true);
let sum = 0n;
for (let i = end; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
range(start, end) {
this.#index(start, true);
this.#index(end, true);
if (start > end) throw new RangeError("reversed range");
return this.prefix(end) - this.prefix(start);
}
total() { return this.prefix(this.length); }
add(index, delta) {
this.#index(index);
if (typeof delta !== "bigint") throw new TypeError("delta must be bigint");
const next = this.#weights[index] + delta;
this.#weight(next);
const staged = [];
for (let i = index + 1; i <= this.length; i += i & -i) {
staged.push([i, this.#tree[i] + delta]);
}
this.#weights[index] = next;
for (const [i, value] of staged) this.#tree[i] = value;
}
set(index, value) {
this.#index(index);
this.#weight(value);
this.add(index, value - this.#weights[index]);
}
lowerBound(target) {
if (typeof target !== "bigint") throw new TypeError("target must be bigint");
if (target <= 0n) throw new RangeError("target must be positive");
let index = 0;
let sum = 0n;
let step = 1;
while (step * 2 <= this.length) step *= 2;
for (; step >= 1; step = Math.floor(step / 2)) {
const next = index + step;
if (next <= this.length && sum + this.#tree[next] < target) {
index = next;
sum += this.#tree[next];
}
}
return index;
}
}
function locateTicket(tree, ticket) {
if (typeof ticket !== "bigint") throw new TypeError("ticket must be bigint");
if (ticket < 0n || ticket >= tree.total()) throw new RangeError("ticket out of range");
return tree.lowerBound(ticket + 1n);
}
const labels = ["alpha", "paused", "beta", "gamma"];
const huge = 9007199254740993n;
const tree = new Fenwick([huge, 0n, 3n, 2n]);
const before = [0n, huge - 1n, huge, huge + 2n, huge + 3n]
.map(ticket => labels[locateTicket(tree, ticket)]);
assert.deepEqual(before, ["alpha", "alpha", "beta", "beta", "gamma"]);
tree.set(1, 2n);
tree.add(0, -huge);
const after = [0n, 1n, 2n, 6n].map(ticket => labels[locateTicket(tree, ticket)]);
assert.deepEqual(after, ["paused", "paused", "beta", "gamma"]);
assert.equal(tree.total(), 7n);
assert.throws(() => locateTicket(tree, -1n), RangeError);
assert.throws(() => locateTicket(tree, 7n), RangeError);
assert.throws(() => locateTicket(tree, 1), TypeError);
assert.throws(() => locateTicket(new Fenwick([]), 0n), RangeError);
console.log("before:", before.join(","));
console.log("after:", after.join(","));
console.log("exact ticket adapter: PASS");精确标准输出:
before: alpha,alpha,beta,beta,gamma after: paused,paused,beta,gamma exact ticket adapter: PASS
交给 AI 的下一轮审查任务
不要只问这段树状数组有没有问题。更有效的任务是要求它逐条解释:为什么所有输入都保持非负权重;为什么拒绝更新后两个内部数组仍一致;为什么零平台不能使用小于等于;为什么返回的 index 已经是零基元素位置;为什么 Number 的位运算边界没有被 BigInt 权重掩盖。让它先给一个能失败的反例,再修复,再把反例加入测试。
复杂度也要说清楚计量方式。构造访问线性数量的节点,查询、更新和定位访问对数数量的节点,保存两份数组需要线性数量的槽位;snapshot 本身是线性复制。BigInt 的加减比较还与整数位数有关,因此这里的对数描述是节点访问次数,不是无条件的常数字长耗时保证。固定索引、精确整数和清晰失败语义,比一个没有边界说明的漂亮复杂度符号更接近可维护实现。
核验资料与适用范围
本文的接口契约、现代 JavaScript 实现、反例和测试均为独立编写。算法背景核对了原作者论文的出版社摘要与官方勘误;本文没有照搬早期论文中的索引约定或搜索伪代码。规范引用用于核对语言行为,不替代实测。资料核验日期为 2026 年 10 月 19 日。
Peter M. Fenwick:A new data structure for cumulative frequency tables,1994,用于确认累计频率分解与二进制索引结构的原始背景。
原论文官方勘误,1994,提醒读者早期搜索代码存在需要单独核对的更正,不能只依据转载片段。
ECMAScript 2024:Number.MAX_SAFE_INTEGER,以及 Numeric Types、NumberBitwiseOp,用于核对精确整数与三十二位位运算边界。
Node.js v24.19.0 命令行文档,用于核对严格处理未捕获 Promise 拒绝的运行选项。本文算法是同步的,保留该选项是为了统一示例的执行检查方式。

