算法模板提供了实现。把模板移到题目里时,可以用小样例检查题目对它的前提是否成立。手算样例只需覆盖几个会改变行为的边界。
二分答案
先说清谓词是「从某处开始成立」还是「到某处为止成立」。在整数区间 [0,5] 上,用 P(x)=x≥3 验证返回的是第一个真值 3。再分别检查全真、全假,以及答案等于任一端点的情况。若题意允许无解,先约定全假时返回什么,避免把边界值误当答案。
单调队列
若窗口长度为 2,输入 [4,4,1] 的两个最大值都是 4。这个样例同时检查重复值和过期下标。再试窗口长度为 1 和等于输入长度的情况,分别覆盖每元素一个答案和只有一个答案的两种边界。
Dijkstra
用三条边 1→2: 8、1→3: 2、3→2: 1 检查间接路径能否将距离 8 改进到 3。再加入一个不可达的顶点,确认输出按题目约定处理。若允许负权边,先换用满足题意的最短路算法,见模板的 Bellman–Ford 一节。
The algorithm handbook provides implementations. Before transplanting a template into a solution, try inputs small enough to verify by hand. Pick cases that exercise a change in behavior.
Binary search on the answer
Decide whether the predicate is false-then-true or true-then-false. On the integers [0,5], the predicate P(x)=x≥3 should give a first true value of 3. Try all true, all false and both endpoints as answers. If the problem allows no solution, define the all-false result explicitly before treating an endpoint as an answer.
Monotonic queues
With window length 2 and input [4,4,1], both maxima are 4. This checks duplicate values and expired indices together. Then try window lengths 1 and the full input length, which produce one answer per element and one answer overall respectively.
Dijkstra
Use edges 1→2: 8, 1→3: 2 and 3→2: 1. The indirect route should improve the distance to vertex 2 from 8 to 3. Add an unreachable vertex and verify that the output follows the problem statement. If negative weights are allowed, choose an algorithm that supports them, such as the handbook's Bellman–Ford template.