Local search and neighborhoods
局部搜索与邻域设计
Model feasible assignments, derive exact MAX-CUT move gains, and compare neighborhoods under a declared evaluation budget.
local-searchA move changes what “stuck” means
A solver divides four vertices into two groups, written as 0011. It tries moving each vertex to the other group. Every move makes the score worse, so it stops. Give the solver permission to move two vertices together and the same partition has an immediate improvement.
Local search works with a current complete assignment and edits it through a chosen neighborhood. The desired output is often the assignment itself; the sequence of edits need not be part of the answer. Berkeley’s introduction uses this distinction to separate configuration optimization from finding a route. CS188, section 1.5
This chapter designs the representation, neighborhood and score of a small weighted MAX-CUT problem. Hill climbing studies how to choose improving moves, while simulated annealing studies accepting some worsening moves. Both need the modeling decisions made here.
Specify the assignments before choosing a solver
Let be a finite, undirected graph without self-loops. Each edge is stored once and has a nonnegative weight . A bit assigns vertex to group 0 or 1. Either group is allowed to be empty, and there is no balance constraint. The objective counts edges whose endpoints lie in different groups:
The indicator is 1 when its condition is true and 0 otherwise. Complementing every bit leaves the cut unchanged, so two bit strings can represent the same unlabeled partition. Our implementation keeps both strings to keep the move rules simple.
Define as the assignments obtained by flipping between 1 and distinct bits. A local optimum for maximization satisfies
The neighborhood is part of this statement. A local optimum for need not be one for . Since is contained in , every local optimum is also an local optimum. No implication about the time needed to find one follows from that inclusion.
Consider the cycle with edges and of weight 2, and edges and of weight 3. At 0011, the two weight-3 edges cross, giving 6. Flipping any single vertex loses a crossing edge of weight 3 and gains one of weight 2: the change is −1. Flipping vertices 1 and 2 together gives 0101, where all four edges cross, giving 10. The value 10 is globally optimal here because it equals the total edge weight. This four-vertex calculation says nothing about larger instances.
The exact gain from flipping a single vertex is
Only incident edges change. For a set of flipped vertices, edges with both endpoints in keep their crossing status. Count only edges with exactly one endpoint in :
Adding two single-vertex gains without correcting their shared edge is wrong. In our example, the two gains are −1 and −1, but the combined gain is +4: their crossing weight-3 edge stays crossing rather than being lost twice.
There is a useful guarantee when every single-vertex gain is nonpositive. Write for total edge weight. Summing the gains over all vertices counts every uncut edge positively twice and every cut edge negatively twice:
The left side is nonpositive at an local optimum, so . Nonnegative weights give , hence . This is a worst-case lower bound, not a claim that half is the usual quality or the best known approximation guarantee. It requires all single flips to be permitted and inspected. A budget interruption supplies no such certificate. Wayne’s lecture presents the nonnegative MAX-CUT guarantee. Local Search, slide 23
Hard constraints need separate treatment. If each group must contain exactly two vertices, a single flip is infeasible. Swapping vertices from opposite groups preserves group sizes, but changes the neighborhood and invalidates the preceding single-flip proof. A finite penalty for imbalance also changes the objective; a high penalized score alone does not certify a feasible partition. Decide whether feasibility is enforced by representation, move filtering or an explicit constraint check.
Compute the changed edges and count the work
The complete Python program uses only the standard library. make_graph validates positive vertex count, distinct endpoints, nonnegative integer weights and no repeated undirected edges. Zero-weight edges and isolated vertices are allowed. The search validates an initial sequence of integer bits, and a nonnegative integer candidate budget. Booleans are rejected where integers are required. The small helper functions assume validated graph, state and move arguments.
A sweep examines the neighborhood in a fixed order: single flips first, then pairs in lexicographic vertex order. It retains the first strictly best gain. A complete sweep with no improvement certifies local optimality for the selected neighborhood. When the budget ends partway through a sweep, the program applies the best improving move examined so far, if any, and reports budget. That move need not be best over the whole neighborhood. Only positive gains are accepted, so the current state is also the best state visited.
from itertools import combinations, product
def make_graph(n, edges):
if type(n) is not int or n < 1:
raise ValueError('n must be a positive integer')
adjacent = [[] for _ in range(n)]
stored, seen = [], set()
for u, v, weight in edges:
if (type(u) is not int or type(v) is not int
or not 0 <= u < n or not 0 <= v < n or u == v):
raise ValueError('edges need distinct vertices in range(n)')
if type(weight) is not int or weight < 0:
raise ValueError('weights must be nonnegative integers')
key = tuple(sorted((u, v)))
if key in seen:
raise ValueError('store each undirected edge only once')
seen.add(key)
stored.append((u, v, weight))
adjacent[u].append((v, weight))
adjacent[v].append((u, weight))
return adjacent, stored
def cut_value(graph, state):
return sum(w for u, v, w in graph[1] if state[u] != state[v])
def gain(graph, state, move):
# Helpers assume a valid state and distinct, in-range move vertices.
moved = set(move)
delta = visits = 0
for u in move:
for v, w in graph[0][u]:
visits += 1
if v not in moved:
delta += w if state[u] == state[v] else -w
return delta, visits
def moves(n, k):
for size in range(1, k + 1):
yield from combinations(range(n), size)
def search(graph, initial, k=1, budget=100):
n = len(graph[0])
state = list(initial)
if len(state) != n or any(type(b) is not int or b not in (0, 1)
for b in state):
raise ValueError('initial must contain n integer bits')
if type(k) is not int or k not in (1, 2):
raise ValueError('k must be 1 or 2')
if type(budget) is not int or budget < 0:
raise ValueError('budget must be a nonnegative integer')
value = cut_value(graph, state)
evaluations = visits = accepted = 0
while True:
best_gain, best_move, complete = 0, None, True
for move in moves(n, k):
if evaluations == budget:
complete = False
break
delta, work = gain(graph, state, move)
evaluations += 1
visits += work
if delta > best_gain:
best_gain, best_move = delta, move
if best_move is None:
status = 'local-optimum' if complete else 'budget'
break
for u in best_move:
state[u] ^= 1
value += best_gain
accepted += 1
if not complete:
status = 'budget'
break
return {'state': tuple(state), 'value': value, 'status': status,
'evaluations': evaluations, 'edge_visits': visits,
'accepted': accepted}
graph = make_graph(4, [(0, 1, 2), (1, 2, 3),
(2, 3, 2), (3, 0, 3)])
start = (0, 0, 1, 1)
assert cut_value(graph, start) == 6
assert [gain(graph, start, (v,))[0] for v in range(4)] == [-1] * 4
assert gain(graph, start, (1, 2))[0] == 4
for k in (1, 2):
result = search(graph, start, k=k, budget=10)
print(k, result['value'], result['status'],
result['evaluations'], result['edge_visits'])
# Exhaustive enumeration certifies this tiny instance only.
optimum = max(cut_value(graph, x) for x in product((0, 1), repeat=4))
assert optimum == 10
assert search(graph, start, k=2, budget=20)['status'] == 'local-optimum'
assert search(graph, start, budget=0)['status'] == 'budget'
The printed columns are neighborhood size limit, final value, stopping reason, candidate evaluations and incident-edge visits:
| Value | Reason | Candidates | Edge visits | |
|---|---|---|---|---|
| 1 | 6 | local-optimum | 4 | 8 |
| 2 | 10 | budget | 10 | 32 |
The second run has reached the optimum, but its own search has not completed a no-improvement sweep at the new state. The separate exhaustive check certifies the tiny example. Keeping those two forms of evidence separate prevents a fortunate answer from being mistaken for a search certificate.
A full objective evaluation scans edges. A single-flip gain scans entries; a two-flip gain scans , including their shared edge twice for membership checks but never adding its weight. Across a complete single-flip sweep there are candidates and visits. Adding all pairs gives candidates and visits. Each vertex appears in pairs, which explains the second count.
Including candidate bookkeeping, a sweep costs for and for , assuming constant-time integer arithmetic and set operations. The graph takes storage; the search uses extra storage and generates moves lazily. Very large integer weights add arithmetic costs. A complete run may require many sweeps even though each accepted move strictly increases the value: the elementary bound of at most accepted moves for integer weights depends on the numerical weight sum, not just its binary encoding length.
Poole and Mackworth describe the broader tradeoff between selecting the best available move and taking cheaper steps, including updating scores only where an assignment changed. The adjacency-based gain calculation above is an original implementation of that principle for this graph. Foundations of Computational Agents, section 4.6.3
Compare results at a declared budget
“Ten iterations” is ambiguous: one iteration might inspect one candidate or thousands. Our table fixes at most ten candidate evaluations per run and also reports edge visits. Those ten candidates cost different amounts in the two neighborhoods. Graph construction and the initial full score are outside the candidate budget; the exhaustive oracle is validation work and is also excluded. A time-based comparison must include the preparation costs that the application actually pays.
For a reproducible small comparison, run both settings from each of the 16 initial bit strings of this graph, with budget 10 and the code’s fixed tie order. The outcomes are below. The value 10 and value 6 columns count runs; the final column counts total edge visits:
| Runs with value 10 | Runs with value 6 | Mean value | Total edge visits | |
|---|---|---|---|---|
| 1 | 14 | 2 | 9.5 | 240 |
| 2 | 16 | 0 | 10 | 512 |
This is an exhaustive set of starts for one constructed instance. It establishes neither a distribution of real problems nor a speed ranking. For larger experiments, pair the same starts and instances across methods, predeclare budgets and restart rules, report outcome distributions, and retain failed or interrupted runs. For randomized methods, record seeds and repeat across seeds. Parameter tuning needs different instances from final evaluation.
On a graph whose optimum is unknown, the best score found is a lower bound on the maximization optimum, not the optimum itself. Here is a simple certified upper bound; stronger bounds may require another algorithm. Report the bound and its origin with any gap. If , every cut scores zero, and a relative ratio with zero denominator is undefined.
Strict improvements terminate on a finite state space, but may stop below the global optimum. Enlarging the neighborhood can remove a particular local optimum while making each sweep more expensive. An unsatisfied constraint at a local optimum does not prove that the constraint problem has no solution. Poole and Mackworth distinguish that failure to find a solution from proving unsatisfiability. Section 4.6.1
Check the model before trusting the score
- At
0011, what happens when only vertex 1 moves, and when vertices 1 and 2 move together? - A completed single-flip search on a nonnegative graph returns value 18 and total edge weight 30. What can be certified about the optimum? Does
budgetsupport the same conclusion? - Both groups must contain exactly two vertices. Which of the program’s pair flips preserve feasibility, and why can the original one-flip proof no longer be used?
- Reproduce the 16-start comparison. Why does the result fail to prove that it runs faster? What status should a budget of zero return?
Answers and checks
- Flipping vertex 1 gives
0111: gain −1 and value 5. Flipping 1 and 2 gives0101: gain +4 and value 10. The edge between 1 and 2 remains crossing in the combined move. - The returned cut proves . Checking every single flip supplies the half-optimum theorem; the numerical upper bound 30 is tighter than the derived bound 36. A budget stop still gives the feasible cut and total-weight upper bound, but does not certify local optimality or the theorem’s premise. If the cut separately satisfies , that observed inequality independently implies the half-optimum bound.
- Flip one vertex from each current group. Flipping two vertices from the same group changes the sizes. Single flips are forbidden, so the required inequalities for all individual vertices are unavailable. The implementation must filter moves before it can solve the balanced variant.
- The table gives 14 versus 16 optimum-valued runs, but 240 versus 512 incident-edge visits. Candidate counts do not equal elapsed time or equal arithmetic work. A zero budget returns the unchanged initial partition with
budget, zero candidates and zero accepted moves. It has not inspected the neighborhood.
Separate a neighborhood design from a search policy
The four-vertex example, gain evaluator and budget experiment in this chapter were constructed for teaching. They are not a published MAX-CUT benchmark. The repository tests recompute objective differences by exhaustive bit-mask enumeration, inspect all four-vertex graphs whose six possible edges have weights 0, 1 or 3, and check solver certificates against independent full enumeration.
For another problem, write down its legal assignments and moves before importing a search policy. Keep a slow full scorer beside the incremental one during development: their answers should agree after each move, including moves that touch the same constraint twice. A score drift of one unit can change a tie, alter the trajectory and invalidate a claimed local optimum. The next chapters use the same distinction between the state model and the rule that chooses the next state.
Make a prediction, then check
A run exhausts its budget and returns a partition. What can be directly asserted?
Learning objectives
- Specify states, feasibility and neighborhoods, and distinguish local optima with one- and two-flip counterexamples.
- Derive and independently check MAX-CUT gains, state the half-optimum bound conditions, and interpret fixed-budget comparisons.
Prerequisites & connections
Explore related knowledge →References
- CS188 Textbook: 1.5 Local Search
UC Berkeley CS188 course staff - Artificial Intelligence: Foundations of Computational Agents, third edition, 4.6 Local Search
David L. Poole; Alan K. Mackworth - Local Search: Algorithm Design lecture slides
Kevin Wayne · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check:primary-source locations,original executable examples,independent finite-state oracles,bilingual review and a second Codex agent cross-check;not independent human peer review.
- Reread both languages for feasibility, singleton and set gains, nonnegative proof, strict improvement, partial-budget rules, complexity and four answers; matched equations, code and six section anchors.
- Seven tests passed: all16states and10moves on729four-vertex weight assignments against an independent full scorer;64unweighted graphs under complete and limited searches, certificates, shared-edge correction,16-start table, boundaries and input preservation.
- Root reread bilingual modeling,gain sums,nonnegative half-optimum bound,partial budgets and work counts; another Codex agent independently checked1920budgeted searches on160sparse graphs of1–8vertices,all passing.
- Paired code,display formulas and main anchors match. All48search checks and101article Python programs passed. Reviews are AI technical checks,not independent human peer review.
- Static build found a same-line details/summary MDX parsing error. Split opening tags onto separate lines only; prose,equations and code are unchanged. Targeted inspection completed and hashes rebound.
- After mobile screenshots, shortened Chinese headers and clarified run-count/total-edge-visit columns in both local-search articles. Algorithms,equations,values and conditions are unchanged; targeted rereading completed.
Source locations checked:
- CS188 Textbook: 1.5 Local Search · Read introductory lines90–95: complete assignments and configuration rather than route output. Claims about finite randomized completeness in later sections were not reused.
- Artificial Intelligence: Foundations of Computational Agents, third edition, 4.6 Local Search · Read4.6.1 lines62–81 for local versus global optima and failure to prove unsatisfiability;4.6.3 lines109–122 for per-step work and updates affecting only related constraints. Original MAX-CUT delta implementation independently tested.
- Local Search: Algorithm Design lecture slides · Read PDF cover dated2017-07-25 and slides21–24,26: undirected MAX-CUT, single-flip nonnegative bound and k-flip neighborhoods. Re-derived all-vertex gain-sum proof; no large-instance benchmark or current approximation record claimed.
Related topics