AI 写的 Li Chao 树同值时选对了吗?用 JavaScript 审查 BigInt 离散最小值查询
审查 AI 写出的算法代码时,最危险的往往不是明显的语法错误,而是代码已经能跑、普通样例也全过,却没有回答边界语义。本文把问题限定为一个可核验的工程组件:维护若干条 BigInt 仿射直线,在预先声明的有限坐标集合上查询最小值,并且稳定返回最早插入的获胜直线编号。我们不假设斜率有序,也不假设查询坐标等间距。

先审契约,再审递归
Li Chao 树围绕逐层保留候选直线来维护下包络。算法设计者 Chao Li 的算法说明与分析预印本给出了中点竞争和路径查询的描述。本文在此基础上自行实现有限坐标版本,并补充稳定编号、严格类型检查与私有数据边界。这里没有复制论文的数值区间实现,也不声称论文替本文的接口细节作了保证。
真正要盯住的有四个问题:比较发生在原始坐标还是压缩后的排名;中点赢家是否仅相对于当前两条候选;同值时能否稳定找到正确编号;空树和非法查询是否被混为一谈。只看到树高是对数级,就认可整段实现,容易漏掉这些与业务结果直接相关的差异。
下面九个代码块均为完整、独立的 CommonJS 程序,已在 Node.js v24.19.0 执行。把每块分别保存成 example-01.cjs 至 example-09.cjs,用 node 加文件名运行即可。Node.js 官方模块文档明确说明 .cjs 使用 CommonJS;断言使用官方严格断言接口。代码块后给出的都是实际标准输出。
示例一:把返回值和归属一起定义清楚
先规定这棵树到底承诺什么。构造器接收非空的 BigInt 数组,把它看作未来允许查询的有限坐标集合。坐标可以无序,可以重复,也可以相隔极远。每次成功加入整条仿射直线后,方法返回从零开始的 BigInt 编号;编号按照成功插入的先后递增,与直线后来放在哪个节点无关。查询返回新的普通对象,里面同时包含最小值和获胜编号。若该坐标合法但还没有任何直线,则返回 null。这个约定使调用者能区分没有候选、候选值为零,以及输入坐标根本不在声明范围内。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
const tree = new DiscreteLiChao([-3n, 0n, 2n, 7n]);
assert.equal(tree.query(0n), null);
assert.equal(tree.add(-2n, 4n), 0n);
assert.equal(tree.add(1n, 1n), 1n);
const answers = [-3n, 0n, 2n, 7n].map(x => tree.query(x));
assert.deepStrictEqual(answers, [
{ value: -2n, id: 1n }, { value: 1n, id: 1n },
{ value: 0n, id: 0n }, { value: -10n, id: 0n }
]);
console.log(answers.map(a => `${a.value}:${a.id}`).join(' '));运行输出:
-2:1 1:1 0:0 -10:0
读插入函数时,应先找到交换,再看递归分支。当前节点保留在中间坐标更优的直线;暂时落败的直线只有在某端点重新胜出时才继续下沉。查询不能只检查叶子,也不能直接相信根节点,而要比较实际访问路径上所有已存直线。下文每个代码块都重复完整实现,因此可以独立保存为对应的 .cjs 文件运行,不需要先执行前一个示例。
示例二:坐标去重与私有副本不是装饰
离散树的边界是排好序的坐标下标,而不是坐标本身。把一万个重复坐标保留成一万个叶子,不仅浪费空间,也让复杂度中的规模含义变得模糊。这里先复制数组,检查复制后的每一项,再去重并排序。先复制还有一个实际作用:稀疏数组中的空位会变成 undefined,随后明确被拒绝,不会被 some 跳过去。排序比较器返回 Number 类型的负一、零或一,不能直接返回两个 BigInt 的差。ECMAScript 的排序比较过程会把比较器返回值转换成 Number,这与直接返回 BigInt 不兼容。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
const input = [10n, -5n, 10n, 0n];
const original = [...input];
const tree = new DiscreteLiChao(input);
assert.deepStrictEqual(input, original);
assert.equal(tree.coordinateCount, 3);
input.fill(99n);
input.push(123n);
tree.add(2n, -3n);
assert.deepStrictEqual(tree.query(10n), { value: 17n, id: 0n });
assert.throws(() => tree.query(99n), RangeError);
const answer = tree.query(-5n);
answer.value = 999n;
answer.id = 999n;
assert.deepStrictEqual(tree.query(-5n), { value: -13n, id: 0n });
console.log('3 coordinates; copies isolated');运行输出:
3 coordinates; copies isolated
私有字段阻止外部替换内部坐标表;查询又只返回包含原始值的新对象,调用方改写结果不会污染下一次查询。接口让斜率和截距直接以 BigInt 参数传入,不保留调用方的可变直线对象。这里的副本策略针对普通数组与原始值,不承诺隔离带恶意迭代器或访问器的输入副作用。审查接口时把边界说清楚,比泛泛声称深拷贝更有用。
示例三:相等时必须比较原始插入编号
AI 生成的实现经常在插入时用严格小于,在查询时用小于等于,看起来每处都合理,合在一起却没有稳定的归属语义。本文统一比较二元组:先比函数值,值相同再比编号,编号小者获胜。完全重复的直线也会获得新编号,但它永远不会挤走较早的相同直线。这个规则必须同时进入中点交换、端点下沉和路径汇总,不能只在最终输出时补一层排序,否则正确的旧编号可能早已被错误丢弃。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
const tree = new DiscreteLiChao([-2n, 0n, 2n]);
tree.add(5n, 7n);
tree.add(-3n, 7n);
tree.add(5n, 7n);
assert.deepStrictEqual(tree.query(0n), { value: 7n, id: 0n });
assert.deepStrictEqual(tree.query(-2n), { value: -3n, id: 0n });
assert.deepStrictEqual(tree.query(2n), { value: 1n, id: 1n });
tree.add(5n, 6n);
assert.deepStrictEqual(tree.query(-2n), { value: -4n, id: 3n });
assert.deepStrictEqual(tree.query(0n), { value: 6n, id: 3n });
assert.deepStrictEqual(tree.query(2n), { value: 1n, id: 1n });
assert.equal(tree.size, 4n);
console.log('stable ties; 4 successful insertions');运行输出:
stable ties; 4 successful insertions
编号不等于树里当前存活的节点数。某条新直线可能在所有声明坐标上都更差,插入后没有新增节点,但这次成功操作依然消耗一个编号。因此 size 在这里表示成功插入次数,且类型也是 BigInt;它不表示下包络的段数,更不表示仍可单独删除的直线数量。
示例四:大整数的精确性不能靠最后再补救
离散 Li Chao 树没有必要求交点。若先把大整数转成 Number,再用浮点除法判断交点在哪一侧,已经丢掉的信息无法在最后转回 BigInt 时恢复。这里所有函数求值、截距以及比较都保留在 BigInt 域内;只有数组下标与中点下标使用 Number。两者职责分开,代码中出现 Math.floor 并不意味着对业务坐标做了浮点近似。下面用七十位数量级的坐标构造精确交会,专门检查相等点和紧邻整数点,而不是只测宽松的小数近似。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
const H = 10n ** 70n;
const tree = new DiscreteLiChao([-H, 0n, H, H + 1n]);
tree.add(H, 1n - H * H);
tree.add(0n, 1n);
tree.add(-H, 1n + H * H);
assert.deepStrictEqual(tree.query(H), { value: 1n, id: 0n });
assert.deepStrictEqual(tree.query(H + 1n), { value: 1n - H, id: 2n });
assert.deepStrictEqual(tree.query(-H), { value: 1n - 2n * H * H, id: 0n });
assert.deepStrictEqual(tree.query(0n), { value: 1n - H * H, id: 0n });
console.log('huge integers remain exact');运行输出:
huge integers remain exact
BigInt 表示整数,不自动表示任意实数,也不会把错误的建模变正确。价格如果带小数,需要调用者先约定精确的整数单位;来自 JSON 的大整数通常也应以字符串保存,再在边界上显式解析。本文的接口故意拒绝隐式转换,避免一个已经被 Number 舍入的输入伪装成精确数据。
示例五:空树、未知坐标和错误输入分别处理
错误顺序是契约的一部分。查询必须先检查类型,再验证坐标是否声明,最后才判断有没有候选。否则空树会把未知坐标也回答成 null,让开发阶段的调用错误藏到生产数据进入之后。空坐标集合没有任何合法查询点,本文直接拒绝构造;这与非空坐标集合上尚未添加直线的空树不同。失败的参数校验应发生在修改根节点和递增编号之前,保证用户修正输入后,编号仍然可以稳定对应成功记录。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
assert.throws(() => new DiscreteLiChao([]), RangeError);
assert.throws(() => new DiscreteLiChao([1n, 2]), TypeError);
assert.throws(() => new DiscreteLiChao(new Array(2)), TypeError);
assert.throws(() => new DiscreteLiChao(new Set([1n])), TypeError);
const tree = new DiscreteLiChao([0n]);
assert.equal(tree.query(0n), null);
assert.throws(() => tree.query(1n), RangeError);
assert.throws(() => tree.query(0), TypeError);
assert.throws(() => tree.add(1, 0n), TypeError);
assert.throws(() => tree.add(1n, '0'), TypeError);
assert.equal(tree.size, 0n);
assert.equal(tree.add(2n, -4n), 0n);
assert.throws(() => tree.query(-1n), RangeError);
assert.deepStrictEqual(tree.query(0n), { value: -4n, id: 0n });
console.log('input errors are distinct; ids stay intact');运行输出:
input errors are distinct; ids stay intact
示例只承诺正常参数错误不改变树,不把进程内存耗尽等运行时灾难描述成事务回滚。若要开放给不可信请求,还需要在外围限制坐标数量、插入次数和整数位数。精确运算解决数值正确性,不自动解决计算资源耗尽。
示例六:非均匀坐标与乱序斜率交给独立扫描判断
离散化不是把坐标间距强行变成一。树按坐标下标分半,但求值仍然使用原始坐标。负一万和负三可能相邻,却仍是两个数值差距很大的位置。下面的参考答案逐条计算所有已插入直线,不读取树节点,也不复用树的比较函数。每次插入之后立刻检查全部声明坐标,这样可以发现只在中间状态发生、随后又被更优直线掩盖的错误。插入斜率完全无需单调,这正是这种结构在增量场景中的价值。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
const xs = [-10000n, -3n, -2n, 0n, 11n, 99999n];
const lines = [[7n, 4n], [-5n, 8n], [0n, -3n], [7n, -9n], [-5n, 8n]];
const tree = new DiscreteLiChao(xs);
let checks = 0;
for (let count = 1; count <= lines.length; count++) {
tree.add(...lines[count - 1]);
for (const x of xs) {
let expected = null;
for (let j = 0; j < count; j++) {
const value = lines[j][0] * x + lines[j][1];
if (expected === null || value < expected.value) expected = { value, id: BigInt(j) };
}
assert.deepStrictEqual(tree.query(x), expected);
checks++;
}
}
console.log(`${checks} prefix queries agree`);运行输出:
30 prefix queries agree
参考实现只在严格更小时替换答案,因为它按插入顺序扫描,遇到相等值自然保留较早编号。这与被测实现显式比较编号的写法不同,能降低两边复制同一个错误的概率。独立性并不要求复杂;对于验证,朴素而清楚的慢算法通常更可信。
示例七:放进动态规划,核对业务层等价变换
数据结构自身正确,接入时仍可能错一项。考虑转移代价为前序状态值、两坐标差的平方,以及前序状态固定费用之和。展开平方后,每个前序状态对应斜率为负二倍前序坐标、截距为前序状态值加前序坐标平方再加固定费用的一条直线;查询结果再加当前坐标平方即可。必须先查询再插入当前状态,才能维持只允许使用更早状态的约束。下面用直接二重循环核对完整状态序列,坐标刻意乱序,费用也允许负数。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
const xs = [4n, -3n, 9n, 0n, -3n, 12n];
const fees = [2n, -1n, 5n, 0n, 3n, -2n];
const tree = new DiscreteLiChao(xs);
const fast = [0n], slow = [0n];
tree.add(-2n * xs[0], xs[0] * xs[0] + fees[0]);
for (let i = 1; i < xs.length; i++) {
fast[i] = xs[i] * xs[i] + tree.query(xs[i]).value;
let best = null;
for (let j = 0; j < i; j++) {
const d = xs[i] - xs[j];
const value = slow[j] + d * d + fees[j];
if (best === null || value < best) best = value;
}
slow[i] = best;
tree.add(-2n * xs[i], fast[i] + xs[i] * xs[i] + fees[i]);
}
assert.deepStrictEqual(fast, slow);
console.log(fast.map(String).join(' '));运行输出:
0 51 27 18 27 41
这个例子只恢复最小代价,没有把树的编号直接当成最终路径。若需要重建决策链,可以在每轮查询时保存获胜编号,并维护编号与状态索引的明确映射。不要等全部插入完成后再重新查询历史状态,因为那时的候选集合已经变化,得到的可能是未来状态。
示例八:固定种子的随机差分测试
随机测试要同时控制可重现性与覆盖面。下面用固定种子的整数发生器选择输入,再在普通尺度与超大尺度之间切换。所有业务数值都从安全的小整数转成 BigInt 后再扩大,避免测试生成器自身先丢精度。这些轮次合起来覆盖负数、零、普通与巨大坐标、重复坐标、随机斜率和截距,并定期重复已有直线。每次成功插入之后,对完整坐标集合执行线性扫描比对,测试的对象是整段增量历史,不只是最终结果。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
let seed = 0x5a17c9e3;
function rnd(n) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed % n; }
function signed(n) { return BigInt(rnd(2 * n + 1) - n); }
let checks = 0;
for (let round = 0; round < 40; round++) {
const scale = round % 2 === 0 ? 1n : 10n ** 55n;
const input = [-scale, 0n, scale];
for (let i = 0; i < 10; i++) input.push(signed(20) * scale + signed(3));
input.push(input[0]);
const xs = [...new Set(input)];
const tree = new DiscreteLiChao(input), lines = [];
for (const x of xs) assert.equal(tree.query(x), null);
for (let step = 0; step < 55; step++) {
const line = step > 0 && step % 7 === 0
? [...lines[rnd(lines.length)]]
: [signed(25) * scale + signed(2), signed(40) * scale * scale + signed(7)];
assert.equal(tree.add(...line), BigInt(step));
lines.push(line);
for (const x of xs) {
let expected = null;
for (let i = 0; i < lines.length; i++) {
const value = lines[i][0] * x + lines[i][1];
if (expected === null || value < expected.value) expected = { value, id: BigInt(i) };
}
assert.deepStrictEqual(tree.query(x), expected);
checks++;
}
}
}
console.log(`${checks} randomized queries agree`);运行输出:
26785 randomized queries agree
固定种子并不是概率证明,也没有覆盖任意位数和任意输入长度。它的作用是让回归失败能够稳定复现。真正定位问题时,应把失败轮次、插入前缀与查询坐标留下,再缩减成小反例。特别要保留获胜编号的断言,只比较最小值会漏掉同值归属的错误。
示例九:穷举小域,追查平局与覆盖顺序
随机大整数容易制造数值极端,却不一定经常命中完全相等。最后把斜率与截距都限制在负一到一,穷举长度为三的全部插入序列,并在每个前缀查询五个坐标。序列允许重复,所以相同直线、平行直线、交点落在查询坐标上,以及旧候选被交换到子树等情况会反复出现。小域穷举和随机差分各自解决不同问题:前者密集检查退化情形,后者扩大尺度与坐标分布。
'use strict';
const assert = require('node:assert/strict');
class DiscreteLiChao {
#xs; #root = null; #next = 0n;
constructor(coordinates) {
if (!Array.isArray(coordinates)) throw new TypeError('coordinates must be an array');
const copy = [...coordinates];
if (copy.some(x => typeof x !== 'bigint')) throw new TypeError('coordinates must be BigInt');
if (copy.length === 0) throw new RangeError('coordinate set must not be empty');
this.#xs = [...new Set(copy)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
get coordinateCount() { return this.#xs.length; }
get size() { return this.#next; }
#value(line, x) { return line.m * x + line.b; }
#better(a, b, x) {
const av = this.#value(a, x), bv = this.#value(b, x);
return av < bv || (av === bv && a.id < b.id);
}
add(m, b) {
if (typeof m !== 'bigint' || typeof b !== 'bigint') throw new TypeError('coefficients must be BigInt');
const line = { m, b, id: this.#next };
this.#root = this.#put(this.#root, line, 0, this.#xs.length - 1);
this.#next += 1n;
return line.id;
}
#put(node, line, lo, hi) {
if (node === null) return { line, left: null, right: null };
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#better(line, node.line, this.#xs[mid])) {
[line, node.line] = [node.line, line];
}
if (lo === hi) return node;
if (this.#better(line, node.line, this.#xs[lo])) {
node.left = this.#put(node.left, line, lo, mid);
} else if (this.#better(line, node.line, this.#xs[hi])) {
node.right = this.#put(node.right, line, mid + 1, hi);
}
return node;
}
query(x) {
if (typeof x !== 'bigint') throw new TypeError('x must be BigInt');
let lo = 0, hi = this.#xs.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.#xs[mid] < x) lo = mid + 1;
else hi = mid;
}
if (this.#xs[lo] !== x) throw new RangeError('undeclared coordinate');
const index = lo;
lo = 0; hi = this.#xs.length - 1;
let node = this.#root, best = null;
while (node !== null) {
if (best === null || this.#better(node.line, best, x)) best = node.line;
if (lo === hi) break;
const mid = lo + Math.floor((hi - lo) / 2);
if (index <= mid) { node = node.left; hi = mid; }
else { node = node.right; lo = mid + 1; }
}
return best === null ? null : { value: this.#value(best, x), id: best.id };
}
}
const pool = [];
for (const m of [-1n, 0n, 1n]) for (const b of [-1n, 0n, 1n]) pool.push([m, b]);
const xs = [-2n, -1n, 0n, 1n, 2n];
let sequences = 0, checks = 0;
for (const a of pool) for (const b of pool) for (const c of pool) {
const tree = new DiscreteLiChao(xs), prefix = [];
for (const line of [a, b, c]) {
tree.add(...line); prefix.push(line);
for (const x of xs) {
let best = null;
for (let i = 0; i < prefix.length; i++) {
const value = prefix[i][0] * x + prefix[i][1];
if (best === null || value < best.value) best = { value, id: BigInt(i) };
}
assert.deepStrictEqual(tree.query(x), best); checks++;
}
}
sequences++;
}
console.log(`${sequences} sequences; ${checks} exhaustive queries agree`);运行输出:
729 sequences; 10935 exhaustive queries agree
测试仍然不能替代插入分支的论证。对任意两条仿射直线,它们的差也是仿射函数;比较结果沿递增坐标最多切换一次。加入稳定编号后,非重合直线只是在相等的交点上确定由哪边获胜,完全重合时则始终由同一编号获胜。中点已经落败的候选不可能在两侧同时重新胜出。如果它在两个端点也都落败,就没有必要继续保存它。这个性质正好支持实现里的单分支递归与端点剪枝。
复杂度应该把整数位数也说清楚
设输入数组长度为 K,去重后坐标数为 M,成功插入次数为 N。构造阶段复制和去重,然后排序;按通常比较排序模型,排序需要 O(M log M) 次比较,另有处理 K 个输入的开销。JavaScript 规范没有为所有引擎承诺具体排序算法或 Set 操作的最坏时间。这里的复杂度描述采用常见实现模型,而不是把规范里没有写出的性能保证当成事实。
单次插入最多经过一条根到叶的路径,每层进行常数次求值与比较;查询先二分确认坐标,再沿一条路径求最小值,所以树层面的操作次数都是 O(log M)。每次插入最多在遇到第一个空位置时创建一个节点,因此实际节点数不超过 N,也不超过完整离散树的 2M−1 个节点。构造完成后,加上坐标表,存储量是 O(M + min(N, M)) 个记录;构造期间的输入副本另需 O(K) 个临时记录。递归栈深度是 O(log M)。这些是记录数和算术操作数,不是字节数或恒定耗时承诺。
ECMAScript 对 BigInt 的定义支持精确整数运算,但任意精度不等于任意长度的运算都一样快。坐标、系数和中间乘积的位数增长后,乘法、加法、比较以及存储都会变贵。上面的对数级描述不能据此解释成独立于整数位数的运行时间。排序比较器的数值返回规则可核对规范中的 CompareArrayElements。
哪些扩展应另开一轮审查
这份实现只支持追加整条直线和查询,不能删除,也不能临时加入新坐标。内部允许丢弃在声明坐标上不可能获胜的候选,所以删除一条获胜直线后,不能简单把某个节点置空再期待其他候选自动回来。新增坐标也可能让先前被剪掉的直线重新有用。若业务需求改变,应保留原始直线记录并重建,或明确选择支持对应操作的另一种结构,而不是在当前类上加一个看起来便利的入口。
区间有效的线段、最大值查询、浮点输入和持久化版本同样需要重新定义契约。尤其不能把函数值比较替换成一个带 epsilon 的模糊比较,然后假定原有严格次序证明仍然成立。本文选择整数和有限坐标,正是为了把每次判断做成可精确复算的证据。
最后给 AI 代码审查留下一条实用标准:一份解释不应只说它采用了某种经典数据结构,还应指出哪些信息会被丢弃、丢弃为何安全、输入变更后哪些保证会失效。稳定编号、未知坐标错误、私有副本和独立扫描测试让这些约束可执行,也使将来修改时更容易知道究竟破坏了哪条承诺。

