main / PvsNP / Complexity / P.lean

1import PvsNP.Basic.Poly
2import PvsNP.Complexity.Time
3
4/-!
5# The class P
6
7`InP L`: some multi-tape machine decides `L` within a polynomial number of steps.
8
9Proved here: the full and the empty language are in P, and P is closed under complement.
10-/
11
12namespace PvsNP
13
14variable {α : Type}
15
16/-- `L ∈ P`: a machine decides `L` in polynomial time. -/
17def InP (L : Language α) : Prop :=
18 ∃ (k : Nat) (M : Machine α k) (T : Nat → Nat), PolyBounded T ∧ DecidesIn M L T
19
20/-- A machine that halts at once, accepting or not as `b` says, touching nothing. -/
21def Machine.const (α : Type) (k : Nat) (b : Bool) : Machine α k where
22 Q := Unit
23 finite := inferInstance
24 start := ()
25 halted _ := true
26 accepting _ := b
27 δ q r := (q, r, fun _ => .stay)
28
29namespace InP
30
31/-- The time bound of a language in P can be taken of the form `c * (n + 1) ^ d`, hence monotone. -/
32theorem polyBound {L : Language α} (h : InP L) :
33 ∃ (k : Nat) (M : Machine α k) (c d : Nat), DecidesIn M L (PvsNP.polyBound c d) := by
34 obtain ⟨k, M, T, ⟨c, d, hT⟩, hM⟩ := h
35 exact ⟨k, M, c, d, hM.mono hT⟩
36
37theorem univ : InP (Language.univ : Language α) :=
38 ⟨0, Machine.const α 0 true, fun _ => 0, PolyBounded.const 0, fun _ =>
39 ⟨rfl, by simp [Machine.const, Language.univ, Machine.init]⟩⟩
40
41theorem empty : InP (Language.empty : Language α) :=
42 ⟨0, Machine.const α 0 false, fun _ => 0, PolyBounded.const 0, fun _ =>
43 ⟨rfl, by simp [Machine.const, Language.empty, Machine.init]⟩⟩
44
45/-- **P is closed under complement**: swap accepting and rejecting halted states. -/
46theorem compl {L : Language α} (h : InP L) : InP L.compl := by
47 obtain ⟨k, M, T, hT, hM⟩ := h
48 refine ⟨k, M.withAccepting (fun q => !M.accepting q), T, hT, fun x => ?_⟩
49 have e : (M.withAccepting (fun q => !M.accepting q)).init (inputTapes x) = M.init (inputTapes x) :=
50 rfl
51 rw [e, Machine.run_withAccepting]
52 refine ⟨(hM x).1, ?_⟩
53 simp only [Machine.withAccepting, Bool.not_eq_eq_eq_not, Bool.not_true, Language.compl_apply,
54 ← (hM x).2, Bool.not_eq_true]
55
56theorem of_compl {L : Language α} (h : InP L.compl) : InP L := by
57 obtain ⟨k, M, T, hT, hM⟩ := h.compl
58 exact ⟨k, M, T, hT, fun x => ⟨(hM x).1, by rw [(hM x).2, Language.compl_compl]⟩⟩
59
60theorem compl_iff {L : Language α} : InP L.compl ↔ InP L := ⟨of_compl, compl⟩
61
62end InP
63
64end PvsNP