f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
311 lines
9.1 KiB
Markdown
311 lines
9.1 KiB
Markdown
---
|
||
id: wiki-2026-0508-csp
|
||
title: Constraint Satisfaction Problems (CSP)
|
||
category: 10_Wiki/Topics
|
||
status: verified
|
||
canonical_id: self
|
||
aliases: [CSP, 제약 충족 문제, AC-3, backtracking, MIP, OR-Tools, scheduling]
|
||
duplicate_of: none
|
||
source_trust_level: A
|
||
confidence_score: 0.93
|
||
verification_status: applied
|
||
tags: [csp, constraint-programming, optimization, scheduling, sat, smt, ortools, backtracking]
|
||
raw_sources: []
|
||
last_reinforced: 2026-05-10
|
||
github_commit: pending
|
||
tech_stack:
|
||
language: Python / C++
|
||
framework: OR-Tools / Z3 / MiniZinc / Choco
|
||
---
|
||
|
||
# Constraint Satisfaction Problems (CSP)
|
||
|
||
## 매 한 줄
|
||
> **"매 rule 의 break X + 매 fill"**. 매 (Variables, Domains, Constraints) 의 triple. 매 backtracking + 매 propagation. 매 modern: OR-Tools, Z3 SMT, MiniZinc. 매 scheduling, 매 routing, 매 puzzle 의 NP-hard 의 practical 접근.
|
||
|
||
## 매 핵심
|
||
|
||
### 매 components
|
||
- **Variables** (X): 매 assignable.
|
||
- **Domains** (D): 매 possible values.
|
||
- **Constraints** (C): 매 relations.
|
||
|
||
### 매 type
|
||
- **Boolean**: SAT.
|
||
- **Integer / discrete**: pure CSP.
|
||
- **Continuous**: linear / convex / nonlinear programming.
|
||
- **Mixed Integer**: MIP.
|
||
- **SMT**: 매 first-order theory.
|
||
|
||
### 매 algorithm
|
||
|
||
#### Backtracking
|
||
- 매 DFS + 매 backtrack on constraint violation.
|
||
- 매 baseline.
|
||
|
||
#### Constraint Propagation
|
||
- **AC-3** (Arc Consistency): 매 inconsistent value 의 prune.
|
||
- **Forward Checking**: 매 variable assignment 시 의 future variable 의 prune.
|
||
|
||
#### Heuristic
|
||
- **MRV** (Minimum Remaining Values): 매 가장 constrained variable first.
|
||
- **Degree heuristic**: 매 매 connected variable.
|
||
- **LCV** (Least Constraining Value): 매 future flexibility maximize.
|
||
|
||
#### Local search
|
||
- **Min-conflicts**: 매 random init + 매 conflict reduce.
|
||
- **Simulated annealing**.
|
||
- **Tabu search**.
|
||
|
||
### 매 SAT (special case)
|
||
- 매 boolean only.
|
||
- 매 CNF form.
|
||
- 매 modern solver: Glucose, MiniSat, Kissat.
|
||
- 매 reduction: 매 다른 NP-complete 의 SAT.
|
||
|
||
### SMT (extended)
|
||
- 매 first-order theory + decision procedure.
|
||
- 매 theory: arithmetic, arrays, bitvectors, strings.
|
||
- 매 Z3, CVC5, Yices.
|
||
|
||
### 매 MIP (Mixed Integer Programming)
|
||
- 매 LP relaxation + branch & bound.
|
||
- 매 Gurobi, CPLEX, OR-Tools.
|
||
|
||
### CP-SAT (modern)
|
||
- 매 OR-Tools 의 hybrid.
|
||
- 매 CP + SAT.
|
||
- 매 매 fastest 의 industrial scheduling.
|
||
|
||
### 매 응용
|
||
1. **Scheduling**: 매 work, 매 sport, 매 exam.
|
||
2. **Routing** (VRP).
|
||
3. **Resource allocation**.
|
||
4. **Configuration** (car options).
|
||
5. **Puzzle** (Sudoku, N-Queens, Zebra).
|
||
6. **Verification** (SMT).
|
||
7. **Compiler** (register allocation).
|
||
|
||
## 💻 패턴
|
||
|
||
### N-Queens (backtracking)
|
||
```python
|
||
def solve_n_queens(n):
|
||
queens = [-1] * n
|
||
|
||
def backtrack(row):
|
||
if row == n: return [queens[:]]
|
||
solutions = []
|
||
for col in range(n):
|
||
if all(queens[r] != col and abs(queens[r] - col) != row - r
|
||
for r in range(row)):
|
||
queens[row] = col
|
||
solutions.extend(backtrack(row + 1))
|
||
return solutions
|
||
|
||
return backtrack(0)
|
||
|
||
print(len(solve_n_queens(8))) # 92
|
||
```
|
||
|
||
### AC-3 (constraint propagation)
|
||
```python
|
||
def ac3(domains, constraints):
|
||
"""매 arc consistency."""
|
||
queue = [(x, y) for (x, y) in constraints]
|
||
while queue:
|
||
(x, y) = queue.pop(0)
|
||
if revise(domains, x, y, constraints):
|
||
if not domains[x]: return False
|
||
for z in neighbors(x):
|
||
if z != y: queue.append((z, x))
|
||
return True
|
||
|
||
def revise(domains, x, y, constraints):
|
||
revised = False
|
||
for vx in list(domains[x]):
|
||
if not any(constraint_holds(x, vx, y, vy, constraints) for vy in domains[y]):
|
||
domains[x].remove(vx)
|
||
revised = True
|
||
return revised
|
||
```
|
||
|
||
### Sudoku (OR-Tools CP-SAT)
|
||
```python
|
||
from ortools.sat.python import cp_model
|
||
|
||
def solve_sudoku(grid):
|
||
model = cp_model.CpModel()
|
||
|
||
# 매 9×9 variable
|
||
cells = [[model.NewIntVar(1, 9, f'c{r}{c}') for c in range(9)] for r in range(9)]
|
||
|
||
# 매 given clues
|
||
for r in range(9):
|
||
for c in range(9):
|
||
if grid[r][c] != 0:
|
||
model.Add(cells[r][c] == grid[r][c])
|
||
|
||
# 매 row / col / box uniqueness
|
||
for r in range(9):
|
||
model.AddAllDifferent(cells[r])
|
||
for c in range(9):
|
||
model.AddAllDifferent([cells[r][c] for r in range(9)])
|
||
for br in range(3):
|
||
for bc in range(3):
|
||
model.AddAllDifferent([cells[3*br + i][3*bc + j] for i in range(3) for j in range(3)])
|
||
|
||
solver = cp_model.CpSolver()
|
||
if solver.Solve(model) == cp_model.OPTIMAL:
|
||
return [[solver.Value(cells[r][c]) for c in range(9)] for r in range(9)]
|
||
return None
|
||
```
|
||
|
||
### Job Shop Scheduling (OR-Tools)
|
||
```python
|
||
from ortools.sat.python import cp_model
|
||
|
||
def schedule_jobs(jobs):
|
||
model = cp_model.CpModel()
|
||
horizon = sum(t for job in jobs for _, t in job)
|
||
|
||
all_tasks = {}
|
||
machine_to_intervals = collections.defaultdict(list)
|
||
|
||
for j_id, job in enumerate(jobs):
|
||
for t_id, (machine, duration) in enumerate(job):
|
||
start = model.NewIntVar(0, horizon, f'start_{j_id}_{t_id}')
|
||
end = model.NewIntVar(0, horizon, f'end_{j_id}_{t_id}')
|
||
interval = model.NewIntervalVar(start, duration, end, f'interval_{j_id}_{t_id}')
|
||
all_tasks[(j_id, t_id)] = (start, end, interval)
|
||
machine_to_intervals[machine].append(interval)
|
||
|
||
# 매 매 machine 의 1 task 만 의 동시.
|
||
for intervals in machine_to_intervals.values():
|
||
model.AddNoOverlap(intervals)
|
||
|
||
# 매 매 job 의 sequence (precedence).
|
||
for j_id, job in enumerate(jobs):
|
||
for t_id in range(len(job) - 1):
|
||
model.Add(all_tasks[(j_id, t_id+1)][0] >= all_tasks[(j_id, t_id)][1])
|
||
|
||
# 매 minimize makespan
|
||
makespan = model.NewIntVar(0, horizon, 'makespan')
|
||
model.AddMaxEquality(makespan, [all_tasks[(j_id, len(job)-1)][1] for j_id, job in enumerate(jobs)])
|
||
model.Minimize(makespan)
|
||
|
||
solver = cp_model.CpSolver()
|
||
solver.Solve(model)
|
||
return solver.ObjectiveValue()
|
||
```
|
||
|
||
### Z3 SMT
|
||
```python
|
||
from z3 import *
|
||
|
||
# 매 example: 매 8-puzzle solvability check
|
||
s = Solver()
|
||
x = [Int(f'x_{i}') for i in range(9)]
|
||
s.add([0 <= xi for xi in x])
|
||
s.add([xi <= 8 for xi in x])
|
||
s.add(Distinct(x))
|
||
|
||
s.add(x[0] == 1)
|
||
s.add(x[1] == 2)
|
||
# ...
|
||
|
||
if s.check() == sat:
|
||
print(s.model())
|
||
```
|
||
|
||
### Vehicle Routing (VRP)
|
||
```python
|
||
from ortools.constraint_solver import routing_enums_pb2, pywrapcp
|
||
|
||
manager = pywrapcp.RoutingIndexManager(num_nodes, num_vehicles, depot)
|
||
routing = pywrapcp.RoutingModel(manager)
|
||
|
||
def distance_callback(from_index, to_index):
|
||
return distance_matrix[manager.IndexToNode(from_index)][manager.IndexToNode(to_index)]
|
||
|
||
transit_idx = routing.RegisterTransitCallback(distance_callback)
|
||
routing.SetArcCostEvaluatorOfAllVehicles(transit_idx)
|
||
|
||
params = pywrapcp.DefaultRoutingSearchParameters()
|
||
params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
|
||
|
||
solution = routing.SolveWithParameters(params)
|
||
```
|
||
|
||
### MiniZinc (declarative)
|
||
```minizinc
|
||
% n-queens.mzn
|
||
int: n = 8;
|
||
array[1..n] of var 1..n: q;
|
||
|
||
constraint forall(i, j in 1..n where i < j) (
|
||
q[i] != q[j] /\
|
||
q[i] - q[j] != i - j /\
|
||
q[i] - q[j] != j - i
|
||
);
|
||
|
||
solve satisfy;
|
||
```
|
||
|
||
### ML-aided heuristic (RL for branching)
|
||
```python
|
||
# 매 modern: RL 의 branching variable selection
|
||
class LearnedHeuristic:
|
||
def __init__(self, model):
|
||
self.model = model
|
||
|
||
def select_variable(self, state):
|
||
"""매 state 의 features → 매 best variable to branch."""
|
||
features = encode_state(state)
|
||
return self.model.predict(features)
|
||
```
|
||
|
||
## 🤔 결정 기준
|
||
| 문제 | Tool |
|
||
|---|---|
|
||
| Boolean SAT | Glucose, Kissat |
|
||
| SMT (math) | Z3, CVC5 |
|
||
| Discrete CSP | OR-Tools CP-SAT |
|
||
| MIP (large) | Gurobi, CPLEX |
|
||
| Scheduling | OR-Tools CP-SAT |
|
||
| Routing | OR-Tools |
|
||
| Continuous | scipy.optimize |
|
||
| Declarative | MiniZinc |
|
||
|
||
**기본값**: OR-Tools CP-SAT 의 baseline (free + fast).
|
||
|
||
## 🔗 Graph
|
||
- 부모: [[Combinatorial-Optimization]] · [[Graph_Theory|Graph-Theory]]
|
||
- 변형: [[MIP]]
|
||
- 응용: [[Scheduling]] · [[Routing]]
|
||
- Tool: [[OR-Tools]]
|
||
- Adjacent: [[Black-Box-Optimization]] · [[Automated-Theorem-Proving]] · [[Bayesian-Statistics]]
|
||
|
||
## 🤖 LLM 활용
|
||
**언제**: 매 scheduling, 매 routing, 매 configuration. 매 verification. 매 puzzle.
|
||
**언제 X**: 매 differentiable problem (gradient descent). 매 black-box (BO).
|
||
|
||
## ❌ 안티패턴
|
||
- **No propagation**: 매 backtracking 만.
|
||
- **MRV / LCV 무시**: 매 inefficient.
|
||
- **Wrong solver for problem class**: 매 SAT for continuous.
|
||
- **No problem decomposition**: 매 huge instance 의 fail.
|
||
- **Constraint 의 redundant 의 add**: 매 solver 의 hint.
|
||
- **Single solution mode**: 매 enumerate 의 expensive.
|
||
|
||
## 🧪 검증 / 중복
|
||
- Verified (Russell-Norvig AI book, OR-Tools docs, Handbook of CP).
|
||
- 신뢰도 A.
|
||
- Related: [[Black-Box-Optimization]] · [[Automated-Theorem-Proving]] · [[Bayesian-Statistics]] · [[Causal-Inference]].
|
||
|
||
## 🕓 Changelog
|
||
| 날짜 | 변경 |
|
||
|---|---|
|
||
| 2026-05-08 | Phase 1 |
|
||
| 2026-05-10 | Manual cleanup — type + algorithm + 매 N-Queens / AC-3 / Sudoku / JSP / VRP code |
|