Your task is to implement and verify the insertion algorithm for a Left-Leaning Red-Black Tree (LLRBT) in Lean. Verification Specification: (1) Preconditions: The input tree must be a valid LLRBT. (2) Postconditions: Functional Correctness (the resulting view is the union of the original set and the inserted value v) and Invariant Maintenance (the resulting tree satisfies is_llrbt, implying BST Order, Black Height preservation, and Color Properties: no Red node has a Red child and no Red node is a right child). Note: The root of the resulting subtree may be Red.

import Mathlib

inductive Color
| Red
| Black
deriving Inhabited, BEq

inductive Node
| Empty : Node
| Tree  (color : Color) (val : Int) (left : Node) (right : Node) : Node
deriving Inhabited

def view (t : Node) : Set Int :=
  match t with
  | Node.Empty => ∅
  | Node.Tree _ v l r => view l ∪ view r ∪ {v}

def is_red (t : Node) : Bool :=
  match t with
  | Node.Tree Color.Red _ _ _ => true
  | _ => false

def is_bst (t : Node) : Prop :=
  match t with
  | Node.Empty => True
  | Node.Tree _ v l r =>
    (∀ x ∈ view l, x < v) ∧
    is_bst l ∧
    (∀ x ∈ view r, x > v) ∧
    is_bst r

-- Black Height: Returns -1 if invalid
def black_height (t : Node) : Int :=
  match t with
  | Node.Empty => 1
  | Node.Tree c _ l r =>
    let lh := black_height l
    let rh := black_height r
    if lh ≠ -1 ∧ rh ≠ -1 ∧ lh = rh then
      if c == Color.Black then lh + 1 else lh
    else
      -1

def satisfies_red_props (t : Node) : Prop :=
  match t with
  | Node.Empty => True
  | Node.Tree c _ l r =>
    satisfies_red_props l ∧
    satisfies_red_props r ∧
    -- Rule 1: No Right-Leaning Red (Matches Dafny)
    (if is_red r then False else True) ∧
    -- Rule 2: No Double Red on Left (Matches Dafny)
    -- Check: If Left is Red, then Left.Left must NOT be Red.
    -- This applies regardless of 'c' (current color).
    (match l with
     | Node.Tree Color.Red _ ll _ =>
       (match ll with | Node.Tree Color.Red _ _ _ => False | _ => True)
     | _ => True)

-- This definition is tricky because LLRBT insert allows the root to be red temporarily or permanently if it's the root of the whole tree (though usually root is black).
-- However, the recursive step needs a weaker invariant.
-- Dafny spec says: "This allows the root to be Red or Black"
def is_llrbt (t : Node) : Prop :=
  is_bst t ∧
  black_height t ≠ -1 ∧
  -- We need to check red properties. Dafny's satisfies_red_props handles recursive checks.
  -- But wait, Dafny's `satisfies_red_props` seems to strictly forbid right-leaning reds everywhere?
  -- Let's re-read Dafny carefully.
  -- satisfy_red_props:
  --   left_ok && right_ok && right_is_black && no_double_red
  --   Right is black: if right is red -> false.
  --   No double red on left: if left is red, left.left cannot be red? No, `l.is_red` then `l.left` check?
  --   Dafny: `match this.left { case Some(l) => if l.is_red then match l.left { case Some(ll) => !ll.is_red ...`
  --   This means: If I am any node, my right child cannot be red. And if my left child is red, IT'S left child cannot be red (no consecutive reds on left edge).
  --   What about Me being Red and Left being Red? Dafny spec doesn't explicitly ban `this.is_red && this.left.is_red` in `satisfies_red_props` itself?
  --   Ah, `no_double_red` checks `this.left` (l) and `l.left` (ll).
  --   So it prevents `Red -> Red` on the left edge.
  satisfies_red_props t

-- Precondition definitions
@[reducible, simp]
def insert_precond (t : Node) : Prop :=
  -- !benchmark @start precond
  is_llrbt t
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def insert (t : Node) (v : Int)
    (h_precond : insert_precond t) : Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def insert_postcond (t : Node) (v : Int) (result : Node)
    (_ : insert_precond t) : Prop :=
  -- !benchmark @start postcond
  is_llrbt result ∧
  view result = view t ∪ {v}
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem insert_postcond_satisfied (t : Node) (v : Int)
    (h_precond : insert_precond t) :
    insert_postcond t v (insert t v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement and verify the fixup_rotate_left algorithm for a Left-Leaning Red-Black Tree (LLRBT) in Lean. Verification Specification: (1) Preconditions: The node must have a right child that is Red (and the node itself typically Black or Red, but the rotation is triggered by a right-leaning Red). (2) Postconditions: Functional Correctness (view/set is preserved) and Invariant Maintenance (BST order is preserved because x < val < right.val order is maintained, Black Height is preserved as the path length logic is symbolic and unchanged, and colors are rotated: the new root takes the old root's color, and the old root becomes Red). Note: This is a standard left rotation to fix a right-leaning Red link.

import Mathlib

inductive Color
| Red
| Black
deriving Inhabited, BEq

inductive Node
| Empty : Node
| Tree  (color : Color) (val : Int) (left : Node) (right : Node) : Node
deriving Inhabited

def view (t : Node) : Set Int :=
  match t with
  | Node.Empty => ∅
  | Node.Tree _ v l r => view l ∪ view r ∪ {v}

def is_red (t : Node) : Bool :=
  match t with
  | Node.Tree Color.Red _ _ _ => true
  | _ => false

def get_color (t : Node) : Color :=
  match t with
  | Node.Tree c _ _ _ => c
  | Node.Empty => Color.Black -- Empty nodes are black

def is_bst (t : Node) : Prop :=
  match t with
  | Node.Empty => True
  | Node.Tree _ v l r =>
    (∀ x ∈ view l, x < v) ∧
    is_bst l ∧
    (∀ x ∈ view r, x > v) ∧
    is_bst r

-- Black Height: Returns -1 if invalid
def black_height (t : Node) : Int :=
  match t with
  | Node.Empty => 1
  | Node.Tree c _ l r =>
    let lh := black_height l
    let rh := black_height r
    if lh ≠ -1 ∧ rh ≠ -1 ∧ lh = rh then
      if c == Color.Black then lh + 1 else lh
    else
      -1

def get_left (t : Node) : Option Node :=
  match t with | Node.Tree _ _ l _ => some l | _ => none

def get_right (t : Node) : Option Node :=
  match t with | Node.Tree _ _ _ r => some r | _ => none

def is_not_empty (t : Node) : Prop :=
  match t with | Node.Empty => False | _ => True

-- Precondition definitions
@[reducible, simp]
def rotate_left_precond (t : Node) : Prop :=
  -- !benchmark @start precond
  match t with
  | Node.Tree _ _ _ r =>
    -- Right child exists and is Red.
    -- (Dafny spec says Right is Red. Node itself can be any color).
    is_red r
  | _ => False
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def rotate_left (t : Node)
    (h_precond : rotate_left_precond t) : Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def rotate_left_postcond (t : Node) (result : Node)
    (_ : rotate_left_precond t) : Prop :=
  -- !benchmark @start postcond
  view result = view t ∧
  is_bst t → is_bst result ∧
  match result, t with
  | Node.Tree c' _ l' _, Node.Tree c _ _ r =>
      -- New root color matches old root color
      c' = c ∧
      -- New left child matches old root and is RED
      (match l' with
       | Node.Tree Color.Red _ _ _ => True
       | _ => False) ∧
      -- Black height preservation
      (black_height t ≠ -1 → black_height result = black_height t)
  | _, _ => False
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem rotate_left_postcond_satisfied (t : Node)
    (h_precond : rotate_left_precond t) :
    rotate_left_postcond t (rotate_left t h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement and verify a right rotation (fixup_rotate_right) for a Left-Leaning Red-Black Tree (LLRBT) in Lean. Verification Specification: (1) Preconditions: The node must have a left child that is Red, and that left child must also have a left child that is Red (Double Red on Left). (2) Postconditions: Functional Correctness (view/set is preserved) and Invariant Maintenance (BST order is preserved, Black Height is preserved, and colors are rotated: the new root takes the old root's color, the old root becomes Red and takes the right position). This fixes the "Double Red" violation by lifting the middle node.

import Mathlib

inductive Color
| Red
| Black
deriving Inhabited, BEq

inductive Node
| Empty : Node
| Tree  (color : Color) (val : Int) (left : Node) (right : Node) : Node
deriving Inhabited

def view (t : Node) : Set Int :=
  match t with
  | Node.Empty => ∅
  | Node.Tree _ v l r => view l ∪ view r ∪ {v}

def is_red (t : Node) : Bool :=
  match t with
  | Node.Tree Color.Red _ _ _ => true
  | _ => false

def get_color (t : Node) : Color :=
  match t with
  | Node.Tree c _ _ _ => c
  | Node.Empty => Color.Black -- Empty nodes are black

def is_bst (t : Node) : Prop :=
  match t with
  | Node.Empty => True
  | Node.Tree _ v l r =>
    (∀ x ∈ view l, x < v) ∧
    is_bst l ∧
    (∀ x ∈ view r, x > v) ∧
    is_bst r

-- Black Height: Returns -1 if invalid
def black_height (t : Node) : Int :=
  match t with
  | Node.Empty => 1
  | Node.Tree c _ l r =>
    let lh := black_height l
    let rh := black_height r
    if lh ≠ -1 ∧ rh ≠ -1 ∧ lh = rh then
      if c == Color.Black then lh + 1 else lh
    else
      -1

def get_left (t : Node) : Option Node :=
  match t with | Node.Tree _ _ l _ => some l | _ => none

def get_right (t : Node) : Option Node :=
  match t with | Node.Tree _ _ _ r => some r | _ => none

def is_not_empty (t : Node) : Prop :=
  match t with | Node.Empty => False | _ => True

-- Precondition definitions
@[reducible, simp]
def rotate_right_precond (t : Node) : Prop :=
  -- !benchmark @start precond
  match t with
  | Node.Tree _ _ l _ =>
    -- Strictly match Dafny/Verus: Only require Left child to be Red.
    -- The Double-Red context is checked by the caller (insert), not this helper.
    is_red l
  | _ => False
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def rotate_right (t : Node)
    (h_precond : rotate_right_precond t) : Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def rotate_right_postcond (t : Node) (result : Node)
    (_ : rotate_right_precond t) : Prop :=
  -- !benchmark @start postcond
  view result = view t ∧
  is_bst t → is_bst result ∧
  match result, t with
  | Node.Tree c' _ _ r', Node.Tree c _ _ _ =>
      -- New root color matches old root color
      c' = c ∧
      -- New right child is Red
      (match r' with
       | Node.Tree Color.Red _ _ _ => True
       | _ => False) ∧
      -- Black height preservation
      (black_height t ≠ -1 → black_height result = black_height t)
  | _, _ => False
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem rotate_right_postcond_satisfied (t : Node)
    (h_precond : rotate_right_precond t) :
    rotate_right_postcond t (rotate_right t h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Longest Common Subsequence (LCS) algorithm and verify its correctness in Lean. Given two strings (or sequences of characters), find the length of the longest subsequence present in both. Postconditions: Result equals the value defined by the standard recursive LCS specification.

import Mathlib

def lcs_spec (s t : List Char) : Nat :=
  match s, t with
  | [], _ => 0
  | _, [] => 0
  | x :: xs, y :: ys =>
    if x = y then 1 + lcs_spec xs ys
    else max (lcs_spec xs (y :: ys)) (lcs_spec (x :: xs) ys)

-- Precondition definitions
@[reducible, simp]
def solve_longest_common_subsequence_precond (s t : List Char) : Prop :=
  -- !benchmark @start precond
  s.length ≤ 3000 ∧ t.length ≤ 3000
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def solve_longest_common_subsequence (s t : List Char)
    (h_precond : solve_longest_common_subsequence_precond s t) : Nat :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def solve_longest_common_subsequence_postcond (s t : List Char) (result : Nat)
    (_ : solve_longest_common_subsequence_precond s t) : Prop :=
  -- !benchmark @start postcond
  result = lcs_spec s t
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem solve_longest_common_subsequence_postcond_satisfied (s t : List Char)
    (h_precond : solve_longest_common_subsequence_precond s t) :
    solve_longest_common_subsequence_postcond s t (solve_longest_common_subsequence s t h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Longest Increasing Subsequence (LIS) algorithm and verify its correctness in Lean. Given a sequence of integers, find the length of the longest subsequence where the elements are strictly increasing. Postconditions: Upper Bound (result ≥ length of any valid strictly increasing subsequence) and Existence (result = length of some valid strictly increasing subsequence). A valid subsequence is defined by a strictly increasing sequence of indices pointing to strictly increasing values.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def longest_increasing_subsequence_precond (seq : List Int) : Prop :=
  -- !benchmark @start precond
  True
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def longest_increasing_subsequence (seq : List Int)
    (h_precond : longest_increasing_subsequence_precond seq) : Nat :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

/-
  Post‑condition auxiliary predicates.
-/

/-- `inc_nat l` states that the list `l` of natural numbers is strictly increasing. -/
def inc_nat (l : List Nat) : Prop :=
  ∀ i j, i < j → i < l.length → j < l.length → l.getD i 0 < l.getD j 0

/-- `inc_vals seq indices` states that the values of `seq` at the given (strictly increasing)
    indices form a strictly increasing sequence. -/
def inc_vals (seq : List Int) (indices : List Nat) : Prop :=
  ∀ i j, i < j → i < indices.length → j < indices.length →
    seq.getD (indices.getD i 0) 0 < seq.getD (indices.getD j 0) 0

/-- `is_valid_is seq indices` bundles the three necessary conditions for a list of indices
    to represent a valid increasing subsequence of `seq`. -/
def is_valid_is (seq : List Int) (indices : List Nat) : Prop :=
  inc_nat indices ∧
  (∀ i, i ∈ indices → i < seq.length) ∧
  inc_vals seq indices

-- Postcondition definitions
@[reducible, simp]
def longest_increasing_subsequence_postcond
    (seq : List Int) (result : Nat)
    (h_precond : longest_increasing_subsequence_precond seq) : Prop :=
  -- !benchmark @start postcond
  (∀ sub : List Nat, is_valid_is seq sub → sub.length ≤ result) ∧
  (∃ sub : List Nat, is_valid_is seq sub ∧ sub.length = result)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem longest_increasing_subsequence_postcond_satisfied
    (seq : List Int) (h_precond : longest_increasing_subsequence_precond seq) :
    longest_increasing_subsequence_postcond
      seq (longest_increasing_subsequence seq h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement Manacher's algorithm for the Longest Palindromic Substring and verify its correctness in Lean using Mathlib. The algorithm identifies the substring of maximal length in input $s$ that reads the same forwards and backwards. The operation proceeds as follows: (1) Transformation: Construct a modified string $T$ by inserting a unique separator (e.g., '#') between every character of $s$ (and at the outer boundaries) to uniformly handle both odd and even length palindromes. (2) Initialization: Maintain an array $P$ where $P[i]$ represents the radius of the palindrome centered at $T[i]$. Initialize a center variable $C$ and a right boundary variable $R$ to $0$. (3) Iteration: Iterate through each index $i$ of $T$. If $i < R$, initialize $P[i]$ using the properties of symmetry around $C$ via the mirror index $i' = 2C - i$, specifically setting $P[i] = \min(R - i, P[i'])$. Otherwise, initialize $P[i]$ to $0$. (4) Expansion: Attempt to expand the palindrome centered at $i$ by checking if characters at $T[i - 1 - P[i]]$ and $T[i + 1 + P[i]]$ are equal. Increment $P[i]$ repeatedly while they match. (5) Boundary Update: If the newly expanded palindrome at $i$ extends beyond $R$ (i.e., $i + P[i] > R$), update the center $C$ to $i$ and the boundary $R$ to $i + P[i]$. (6) Result Extraction: Find the maximum value in $P$ and map its center and radius back to the corresponding start index and length in original string $s$. Use Array UInt8 for input. Specifically, you must prove the following: (1) Functional Correctness: The returned tuple $(start, len)$ defines a valid subrange of $s$, the substring defined by this range satisfies the formal is_palindrome definition (symmetric characters), and for any other valid palindromic substring in $s$, its length is $\le len$. (2) Loop Invariants: You must demonstrate that for every processed center $k < i$, $P[k]$ stores the correct maximal palindrome radius for that center in $T$, and that the current variables $C$ and $R$ consistently mark the rightmost ending palindrome found so far.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def longest_palindromic_substring_precond (s : Array UInt8) : Prop :=
  -- !benchmark @start precond
  s.size ≤ 1000000
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def longest_palindromic_substring (s : Array UInt8)
    (_ : longest_palindromic_substring_precond s) :
    Nat × Nat :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Helper definitions
def is_valid_subrange (s : Array UInt8) (start len : Nat) : Prop :=
  start + len ≤ s.size

-- A sequence slice s[start, start+len) is a palindrome if for all i < len,
-- s[start + i] == s[start + len - 1 - i]
def is_palindrome_slice (s : Array UInt8) (start len : Nat) : Prop :=
  ∀ i, i < len → s.getD (start + i) 0 = s.getD (start + len - 1 - i) 0

-- Postcondition definitions
@[reducible, simp]
def longest_palindromic_substring_postcond
    (s : Array UInt8) (result : Nat × Nat)
    (_ : longest_palindromic_substring_precond s) : Prop :=
  -- !benchmark @start postcond
  let (start, len) := result
  is_valid_subrange s start len ∧
  is_palindrome_slice s start len ∧
  (∀ i l, is_valid_subrange s i l → is_palindrome_slice s i l → l ≤ len)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem longest_palindromic_substring_postcond_satisfied
    (s : Array UInt8) (h_precond : longest_palindromic_substring_precond s) :
    longest_palindromic_substring_postcond
      s (longest_palindromic_substring s h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement Matrix Multiplication and verify its correctness in Lean. Given two valid matrices A (m x n) and B (n x k), compute their product C (m x k). Postconditions: The element at C[i][j] is the dot product of row i of A and column j of B. Preconditions: Matrices must be well-formed (non-empty, rectangular) and dimensions must match (cols(A) == rows(B)). Elements are natural numbers.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def matrix_multiply_precond (A B : List (List Nat)) : Prop :=
  -- !benchmark @start precond
  A.length > 0 ∧
  A.length ≤ 10 ∧ -- Aligned with Dafny/Verus (10)
  (∀ row, row ∈ A → row.length > 0) ∧
  (∀ row, row ∈ A → row.length ≤ 10) ∧
  (∀ i j, i < A.length → j < A.length → (A.getD i []).length = (A.getD j []).length) ∧

  -- Value Bounds (ADDED to match references)
  (∀ row, row ∈ A → ∀ val, val ∈ row → val ≤ 100) ∧
  (∀ row, row ∈ B → ∀ val, val ∈ row → val ≤ 100) ∧

  B.length > 0 ∧
  B.length ≤ 10 ∧
  (∀ row, row ∈ B → row.length > 0) ∧
  (∀ row, row ∈ B → row.length ≤ 10) ∧
  (∀ i j, i < B.length → j < B.length → (B.getD i []).length = (B.getD j []).length) ∧
  (A.getD 0 []).length = B.length
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def matrix_multiply (A B : List (List Nat)) (h_precond : matrix_multiply_precond A B) : List (List Nat) :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

def inner_product (row : List Nat) (col_idx : Nat) (B : List (List Nat)) : Nat :=
  (List.range row.length).foldl (fun acc k => acc + (row.getD k 0) * ((B.getD k []).getD col_idx 0)) 0

-- Postcondition definitions
@[reducible, simp]
def matrix_multiply_postcond (A B : List (List Nat)) (result : List (List Nat)) (h_precond : matrix_multiply_precond A B) : Prop :=
  -- !benchmark @start postcond
  result.length = A.length ∧
  (∀ row, row ∈ result → row.length = (B.getD 0 []).length) ∧
  (∀ i j, i < result.length → j < (result.getD 0 []).length →
    (result.getD i []).getD j 0 = inner_product (A.getD i []) j B)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem matrix_multiply_postcond_satisfied (A B : List (List Nat))
    (h_precond : matrix_multiply_precond A B) :
    matrix_multiply_postcond A B (matrix_multiply A B h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement an algorithm to find the Maximum Bipartite Matching and verify its functional correctness in Lean using Mathlib. Preconditions The input is a Bipartite Graph consisting of two disjoint sets of vertices: Left Set (U) with left_size nodes. Right Set (V) with right_size nodes. The graph is represented as an adjacency list adj (Array of Array Nat) where adj[u] contains a list of neighbors in the Right Set. Requirements: Implement the function max_bipartite_matching which returns the size (number of edges) of the maximum matching. Verification Challenges: (1) Valid Pairing: Proving that the match array maintained by your algorithm correctly maps nodes in the Right Set to their matched partners in the Left Set, and that every recorded match corresponds to a real edge exists in adj. (2) Disjointness: Proving that the algorithm never assigns two different Left-nodes to the same Right-node (and vice-versa). (3) Optimality: Proving that when the algorithm terminates, the matching size is indeed maximal. This usually requires proving Berge's Lemma: a matching is maximum if and only if there is no augmenting path.

import Mathlib

structure MaxMatchingGraph where
  left_size : Nat
  right_size : Nat
  adj : Array (Array Nat)

def MaxMatchingGraph.well_formed (g : MaxMatchingGraph) : Prop :=
  g.adj.size = g.left_size ∧
  ∀ u, u < g.left_size →
    ∀ v, v ∈ g.adj.getD u #[] → v < g.right_size

def MaxMatchingGraph.has_edge (g : MaxMatchingGraph) (u v : Nat) : Prop :=
  u < g.left_size ∧
  v ∈ g.adj.getD u #[]

-- Matching definition
structure Matching where
  edges : List (Nat × Nat)

def Matching.is_valid (m : Matching) (g : MaxMatchingGraph) : Prop :=
  ∀ e, e ∈ m.edges → g.has_edge e.1 e.2

def Matching.is_disjoint (m : Matching) : Prop :=
  ∀ e1 e2, e1 ∈ m.edges → e2 ∈ m.edges → e1 ≠ e2 →
    e1.1 ≠ e2.1 ∧ e1.2 ≠ e2.2

def Matching.size (m : Matching) : Nat :=
  m.edges.length

def is_matching (g : MaxMatchingGraph) (m : Matching) : Prop :=
  m.is_valid g ∧
  m.is_disjoint ∧
  m.edges.Nodup

def is_max_matching_size (g : MaxMatchingGraph) (k : Nat) : Prop :=
  (∃ m, is_matching g m ∧ m.size = k) ∧
  (∀ m, is_matching g m → m.size ≤ k)

-- Precondition definitions
@[reducible, simp]
def max_bipartite_matching_precond (graph : MaxMatchingGraph) : Prop :=
  -- !benchmark @start precond
  graph.well_formed ∧ graph.left_size ≤ 1000 ∧ graph.right_size ≤ 1000
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def max_bipartite_matching (graph : MaxMatchingGraph)
    (h_precond : max_bipartite_matching_precond graph) : Nat :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def max_bipartite_matching_postcond (graph : MaxMatchingGraph) (result : Nat)
    (_ : max_bipartite_matching_precond graph) : Prop :=
  -- !benchmark @start postcond
  is_max_matching_size graph result
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem max_bipartite_matching_postcond_satisfied (graph : MaxMatchingGraph)
    (h_precond : max_bipartite_matching_precond graph) :
    max_bipartite_matching_postcond graph
      (max_bipartite_matching graph h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Pop Max operation for a binary max-heap and verify its correctness in Lean. The operation removes the root (max element), moves the last element to the root, and bubbles it down. Postconditions: Returns max element, heap size decreases by 1, multiset view is view - {max}, and heap invariant is preserved.

import Mathlib

structure BinaryMaxHeap where
  storage : List Int
deriving Inhabited

namespace BinaryMaxHeap

def len (h : BinaryMaxHeap) : Nat :=
  h.storage.length

def get (h : BinaryMaxHeap) (i : Nat) : Int :=
  h.storage.getD i 0

def parent (i : Nat) : Nat := (i - 1) / 2

def is_heap (h : BinaryMaxHeap) : Prop :=
  ∀ i, 0 < i ∧ i < h.len → h.get i ≤ h.get (parent i)

def view (h : BinaryMaxHeap) : Multiset Int :=
  Multiset.ofList h.storage

-- Precondition definitions
@[reducible, simp]
def pop_max_precond (h : BinaryMaxHeap) : Prop :=
  -- !benchmark @start precond
  is_heap h ∧ h.len > 0
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
-- Returns (new_heap, popped_max)
def pop_max (h : BinaryMaxHeap)
    (h_precond : pop_max_precond h) : BinaryMaxHeap × Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def pop_max_postcond (h : BinaryMaxHeap) (result : BinaryMaxHeap × Int)
    (_ : pop_max_precond h) : Prop :=
  -- !benchmark @start postcond
  let (new_h, max_val) := result
  is_heap new_h ∧
  new_h.len = h.len - 1 ∧
  (∀ x ∈ h.view, max_val ≥ x) ∧
  new_h.view = h.view - {max_val}
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem pop_max_postcond_satisfied (h : BinaryMaxHeap)
    (h_precond : pop_max_precond h) :
    pop_max_postcond h (pop_max h h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof

end BinaryMaxHeap


Your task is to implement the Push operation for a binary max-heap and verify its correctness in Lean. The operation inserts a new value at the end and bubbles it up to restore the heap property. Postconditions: Multiset view includes the new element (view = old_view + {v}), heap size increases by 1, and the heap invariant is preserved (parent ≥ child).

import Mathlib

structure BinaryMaxHeap where
  storage : List Int
deriving Inhabited

namespace BinaryMaxHeap

def len (h : BinaryMaxHeap) : Nat :=
  h.storage.length

def get (h : BinaryMaxHeap) (i : Nat) : Int :=
  h.storage.getD i 0 -- Safe access with default

def parent (i : Nat) : Nat := (i - 1) / 2

def is_heap (h : BinaryMaxHeap) : Prop :=
  ∀ i, 0 < i ∧ i < h.len → h.get i ≤ h.get (parent i)

def view (h : BinaryMaxHeap) : Multiset Int :=
  Multiset.ofList h.storage

-- Precondition definitions
@[reducible, simp]
def push_precond (h : BinaryMaxHeap) (v : Int) : Prop :=
  -- !benchmark @start precond
  is_heap h ∧ h.len < 1023 -- Limited capacity as per spec example
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def push (h : BinaryMaxHeap) (v : Int)
    (h_precond : push_precond h v) : BinaryMaxHeap :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def push_postcond (h : BinaryMaxHeap) (v : Int) (result : BinaryMaxHeap)
    (_ : push_precond h v) : Prop :=
  -- !benchmark @start postcond
  is_heap result ∧
  result.len = h.len + 1 ∧
  result.view = h.view + {v}
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem push_postcond_satisfied (h : BinaryMaxHeap) (v : Int)
    (h_precond : push_precond h v) :
    push_postcond h v (push h v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof

end BinaryMaxHeap


Your task is to implement the Maximum Subarray Sum algorithm (Kadane's Algorithm) and verify its correctness in Lean. Given a sequence of integers, find the maximum sum of any contiguous subarray. Postconditions: Result is greater than or equal to the sum of any contiguous subarray, and there exists a contiguous subarray with that sum. Basic case handles empty sequence as sum 0 or handling non-empty requirement. Spec assumes non-empty list.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def maxSubarraySum_precond (seq : List Int) : Prop :=
  -- !benchmark @start precond
  0 < seq.length ∧ seq.length ≤ 100000
  -- !benchmark @end precond

def spec_sum (seq : List Int) (i j : Nat) : Int :=
  ((seq.drop i).take (j - i)).foldl (fun acc x => acc + x) 0

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def maxSubarraySum (seq : List Int) (h_precond : maxSubarraySum_precond (seq)) : Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def maxSubarraySum_postcond (seq : List Int) (result: Int) (h_precond : maxSubarraySum_precond (seq)) : Prop :=
  -- !benchmark @start postcond
  (∀ i j : Nat, i ≤ j → j ≤ seq.length → spec_sum seq i j ≤ result) ∧
  (∃ i j : Nat, i ≤ j ∧ j ≤ seq.length ∧ spec_sum seq i j = result)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem maxSubarraySum_postcond_satisfied (seq: List Int) (h_precond : maxSubarraySum_precond (seq)) :
    maxSubarraySum_postcond (seq) (maxSubarraySum (seq) h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Merge Sort algorithm and verify its correctness in Lean. Given a list of integers, return a new list containing the same elements sorted in non-decreasing order. Postconditions: (1) Output is sorted. (2) Output is a permutation of input. Preconditions: None. Implementation: Recursive divide-and-conquer. Split list into two halves, recursively sort them, then merge the sorted halves. Note: You should use 'partial' or a termination proof for recursion.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def mergeSort_precond (v : List Int) : Prop :=
  -- !benchmark @start precond
  True
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def mergeSort (v : List Int) (h_precond : mergeSort_precond v) : List Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def mergeSort_postcond (v : List Int) (result : List Int) (h_precond : mergeSort_precond v) : Prop :=
  -- !benchmark @start postcond
   List.Sorted (· ≤ ·) result ∧ result.Perm v
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem mergeSort_postcond_satisfied (v : List Int) (h_precond : mergeSort_precond v) :
    mergeSort_postcond v (mergeSort v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Karatsuba Multiplication Algorithm for polynomials and verify its functional correctness in Lean. Given two polynomials A and B represented as coefficient lists, compute their product. Preconditions: 1. Lengths: A and B have equal lengths, which are powers of two (e.g., 2, 4, 8...). 2. Constraints: The sum of lengths is at most 1000. Coefficients are integers between -1,000,000 and 1,000,000. Postconditions: Implement `karatsuba_mul` using the divide-and-conquer approach. (1) Algorithm: - Base Case: Small N (e.g., N=1), use simple multiplication. - Recursive Step: Split A and B into halves (A0, A1, B0, B1). Compute z0 = A0*B0, z2 = A1*B1, and z1 = (A0+A1)*(B0+B1). - Combine: result = z0 + (z1 - z0 - z2)x^m + z2 x^2m. (2) Output: Returns a list of size |A| + |B| - 1. (3) Functional Correctness: Verify that the result matches the standard mathematical convolution of A and B.  Verification Challenges: (1) Algebraic Equivalence: You must prove that the Karatsuba formula mathematically equals the standard polynomial multiplication formula. This typically requires a helper lemma showing (A0+A1)(B0+B1) - A0B0 - A1B1 = A0B1 + A1B0. (2) Termination: Prove that the recursion on list length terminates.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def karatsuba_mul_precond (a b : List Int) : Prop :=
  -- !benchmark @start precond
  a.length > 0 ∧
  b.length > 0 ∧
  a.length + b.length ≤ 1000 ∧
  (∃ k : Nat, 2 ^ k = a.length) ∧
  (∃ k : Nat, 2 ^ k = b.length) ∧
  a.length = b.length ∧
  (∀ c, c ∈ a → -1000000 ≤ c ∧ c ≤ 1000000) ∧
  (∀ c, c ∈ b → -1000000 ≤ c ∧ c ≤ 1000000)
  -- !benchmark @end precond

def spec_poly_mul_coeff (a b : List Int) (k : Nat) : Int :=
  -- Omitted definition for brevity, same as naive
  0 -- placeholder

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def karatsuba_mul (a b : List Int) (h_precond : karatsuba_mul_precond a b) : List Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def karatsuba_mul_postcond (a b : List Int) (result : List Int) (h_precond : karatsuba_mul_precond a b) : Prop :=
  -- !benchmark @start postcond
   result.length = a.length + b.length - 1 ∧
   ∀ k : Nat, k < result.length →
     result.getD k 0 = (List.range (k + 1)).foldl (fun acc i =>
         if i < a.length ∧ k - i < b.length then
           acc + a.getD i 0 * b.getD (k - i) 0
         else acc) 0
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem karatsuba_mul_postcond_satisfied (a b : List Int) (h_precond : karatsuba_mul_precond a b) :
    karatsuba_mul_postcond a b (karatsuba_mul a b h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement Naive Polynomial Multiplication and verify its correctness in Lean. Given two polynomials A and B represented as coefficient lists, compute their product C using the O(N^2) algorithm. Preconditions: 1. Input polynomials are non-empty. 2. Constraints: To simplify verification, the sum of lengths is at most 1000, and every coefficient is between -1,000,000 and 1,000,000. Postconditions: Implement `poly_multiply` to return the product polynomial. (1) Output: Returns a list of size |A| + |B| - 1. (2) Functional Correctness: The coefficients of C must match the mathematical convolution of A and B. Verification Challenges: (1) Accumulation Logic: You must define the convolution sum (sum_{p+q=k} A[p]*B[q]) and prove your loop computes it.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def poly_multiply_precond (a b : List Int) : Prop :=
  -- !benchmark @start precond
  a.length > 0 ∧
  b.length > 0 ∧
  a.length + b.length ≤ 1000 ∧
  (∀ c, c ∈ a → -1000000 ≤ c ∧ c ≤ 1000000) ∧
  (∀ c, c ∈ b → -1000000 ≤ c ∧ c ≤ 1000000)
  -- !benchmark @end precond

def spec_poly_mul_coeff (a b : List Int) (k : Nat) : Int :=
  -- Omitted definition for brevity in this context, but would simulate convolution
  0 -- placeholder

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def poly_multiply (a b : List Int) (h_precond : poly_multiply_precond a b) : List Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def poly_multiply_postcond (a b : List Int) (result : List Int) (h_precond : poly_multiply_precond a b) : Prop :=
  -- !benchmark @start postcond
  result.length = a.length + b.length - 1 ∧
  ∀ k : Nat, k < result.length →
    result.getD k 0 = (List.range (k + 1)).foldl (fun acc i =>
        if i < a.length ∧ k - i < b.length then
          acc + a.getD i 0 * b.getD (k - i) 0
        else acc) 0
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem poly_multiply_postcond_satisfied (a b : List Int) (h_precond : poly_multiply_precond a b) :
    poly_multiply_postcond a b (poly_multiply a b h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement Prim's Algorithm to find the Minimum Spanning Tree (MST) of a connected, undirected, weighted graph and verify its functional correctness in Lean using Mathlib. The graph is represented as an adjacency list with Int weights. Preconditions: You can assume the graph is connected (a path exists between any two nodes). You can assume the graph contains at most 100,000 nodes and edge weights are between -100,000 and 100,000 to prevent integer overflow. Crucially, the graph is a Simple Graph (no parallel edges between the same two nodes). Requirements: Implement the function prim_mst which returns a list of edges (source, target, weight). (1) The returned sequence must contain exactly N-1 edges (where N is the number of nodes). (2) The edges must form a valid Spanning Tree (connecting all nodes with no cycles). (3) Global Optimality: You must prove that the sum of weights of your returned edges is less than or equal to the sum of weights of any other possible spanning tree of the graph. Verification Challenges: (1) The Cut Property: The core of Prim’s correctness. (2) Tree Growth: Proving the invariant that at every step of the algorithm, the set of selected edges forms a single connected tree that is a subset of a valid MST. (3) Termination & Connectivity.

import Mathlib

structure WeightedGraph where
  adj : Array (Array (Nat × Int))

def WeightedGraph.size (g : WeightedGraph) : Nat :=
  g.adj.size

def WeightedGraph.has_edge (g : WeightedGraph) (u v : Nat) (w : Int) : Prop :=
  u < g.size ∧
  ∃ pair, pair ∈ g.adj.getD u #[] ∧ pair.1 = v ∧ pair.2 = w

def WeightedGraph.well_formed (g : WeightedGraph) : Prop :=
  ∀ u, u < g.size →
    -- Bounds check
    (∀ pair, pair ∈ g.adj.getD u #[] → pair.1 < g.size) ∧
    -- Simple graph check (matches Dafny)
    (∀ p1 p2, p1 ∈ g.adj.getD u #[] → p2 ∈ g.adj.getD u #[] → p1.1 = p2.1 → p1 = p2)

structure MSTEdge where
  u : Nat
  v : Nat
  w : Int

-- 1. Validity
def MSTEdge.is_valid (e : MSTEdge) (g : WeightedGraph) : Prop :=
  g.has_edge e.u e.v e.w

-- 2. Connectivity for Solution Edges (Undirected View)
-- Dafny: `edge_in_set` checks (u, v) || (v, u)
def edges_contain (edges : List MSTEdge) (u v : Nat) : Prop :=
  ∃ e, e ∈ edges ∧ ((e.u = u ∧ e.v = v) ∨ (e.u = v ∧ e.v = u))

def path_follows_edges (edges : List MSTEdge) (p : List Nat) : Prop :=
  p.length > 0 ∧
  ∀ i, i + 1 < p.length →
    edges_contain edges (p.getD i 0) (p.getD (i + 1) 0)

def is_connected_with_edges (g : WeightedGraph) (edges : List MSTEdge) : Prop :=
  ∀ u v, u < g.size → v < g.size →
    ∃ p, p.head? = some u ∧ p.getLast? = some v ∧ path_follows_edges edges p

-- 3. Spanning Tree Definition
def is_spanning_tree (g : WeightedGraph) (edges : List MSTEdge) : Prop :=
  edges.length = g.size - 1 ∧
  (∀ e, e ∈ edges → e.is_valid g) ∧
  is_connected_with_edges g edges
  -- Note: |V|-1 edges + Connected implies Acyclic (Tree)

def total_weight (edges : List MSTEdge) : Int :=
  edges.foldl (λ sum e => sum + e.w) 0

-- 4. Optimality (MST)
def is_mst (g : WeightedGraph) (edges : List MSTEdge) : Prop :=
  is_spanning_tree g edges ∧
  ∀ other, is_spanning_tree g other → total_weight edges ≤ total_weight other

-- 5. Graph Connectivity (Precondition)
-- Dafny uses directed edges for the graph path check: `graph_has_any_edge`
def path_follows_graph (g : WeightedGraph) (p : List Nat) : Prop :=
  p.length > 0 ∧
  ∀ i, i + 1 < p.length →
    ∃ w, g.has_edge (p.getD i 0) (p.getD (i + 1) 0) w

def WeightedGraph.is_connected (g : WeightedGraph) : Prop :=
  ∀ u v, u < g.size → v < g.size →
    ∃ p, p.head? = some u ∧ p.getLast? = some v ∧ path_follows_graph g p

def WeightedGraph.weights_bounded (g : WeightedGraph) : Prop :=
  g.size ≤ 100000 ∧
  ∀ u v w, g.has_edge u v w → w ≥ -100000 ∧ w ≤ 100000

-- Precondition definitions
@[reducible, simp]
def prim_mst_precond (graph : WeightedGraph) : Prop :=
  -- !benchmark @start precond
  graph.well_formed ∧
  graph.size > 0 ∧
  graph.is_connected ∧
  graph.weights_bounded ∧
  -- Undirected: if u→v with weight w exists, then so does v→u with the same weight
  (∀ u v w, graph.has_edge u v w → graph.has_edge v u w)
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def prim_mst (graph : WeightedGraph)
    (h_precond : prim_mst_precond graph) : List MSTEdge :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def prim_mst_postcond (graph : WeightedGraph) (result : List MSTEdge)
    (_ : prim_mst_precond graph) : Prop :=
  -- !benchmark @start postcond
  is_mst graph result
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem prim_mst_postcond_satisfied (graph : WeightedGraph)
    (h_precond : prim_mst_precond graph) :
    prim_mst_postcond graph (prim_mst graph h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Push-Relabel Algorithm to find the maximum flow in a directed graph and verify its functional correctness in Lean using Mathlib. Preconditions: You can assume the graph contains at most 1,000 nodes. You can assume edge capacities are between 0 and 100,000. The Source s and Sink t are valid, distinct nodes. Crucially, the graph is a Simple Graph (no parallel edges between the same two nodes), ensuring that capacities between any pair of nodes are unique. Requirements: Implement the function max_flow_value which returns the integer value of the max flow. Algorithm: You must implement the Push-Relabel strategy. This involves maintaining a "Preflow" (where Flow In $\ge$ Flow Out) and a "Height" function for every node. Operations: You should repeatedly perform Push (moving excess flow to a lower neighbor) and Relabel (increasing the height of a node) operations until no nodes have excess flow. Output: The returned value must be equal to the net flow out of the source in a valid maximum flow assignment. Verification Challenges: (1) Height Invariant: Proving that for every edge $(u, v)$ with residual capacity, $height(u) \le height(v) + 1$. This guarantees that the flow never goes "uphill" too steeply, preventing cycles. (2) Preflow to Valid Flow: Unlike augmenting path algorithms, the intermediate state here is invalid (nodes have excess). You must prove that when the algorithm terminates (no active nodes), the Preflow becomes a valid Flow. (3) Termination (Well-Foundedness): Proving the algorithm doesn't run forever is critical in Lean; you likely need a defined measure (e.g., based on heights of active nodes) to prove the operations strictly decrease a well-founded metric.

import Mathlib

structure CapacityGraph where
  adj : Array (Array (Nat × Int))

def CapacityGraph.size (g : CapacityGraph) : Nat :=
  g.adj.size

def CapacityGraph.has_capacity (g : CapacityGraph) (u v : Nat) (c : Int) : Prop :=
  u < g.size ∧
  ∃ pair, pair ∈ g.adj.getD u #[] ∧ pair.1 = v ∧ pair.2 = c

def CapacityGraph.well_formed (g : CapacityGraph) : Prop :=
  ∀ u, u < g.size →
    (∀ pair, pair ∈ g.adj.getD u #[] → pair.1 < g.size) ∧
    -- Unique targets
    (∀ p1 p2, p1 ∈ g.adj.getD u #[] → p2 ∈ g.adj.getD u #[] → p1.1 = p2.1 → p1 = p2)

-- A flow map assigns a flow value to each edge (u, v)
-- We can model this as a function or list of entries.
-- Since the result is just the max flow value, we can keep FlowMap abstract in the spec
-- or define it as `Nat -> Nat -> Int`.
-- Dijkstra and others used abstract/implicit paths. here we need explicit flow values.
def FlowMap := Nat → Nat → Int

def FlowMap.get (f : FlowMap) (u v : Nat) : Int := f u v

def CapacityGraph.respects_capacity (g : CapacityGraph) (f : FlowMap) : Prop :=
  ∀ u v,
    (f.get u v > 0 →
      ∃ c, g.has_capacity u v c ∧ f.get u v ≤ c) ∧
    (f.get u v >= 0) -- Non-negative flow

def flow_out (g : CapacityGraph) (f : FlowMap) (u : Nat) : Int :=
  -- Sum of f(u, v) for all v. Hard to define as sum over infinite/large domain without Finset.
  -- But we can sum over the adjacency list of u.
  -- Since well_formed ensures unique neighbors, we can map adj to flow and sum.
  let neighbors := g.adj.getD u #[]
  neighbors.foldl (λ sum pair => sum + f.get u pair.1) 0

def flow_in (g : CapacityGraph) (f : FlowMap) (u : Nat) : Int :=
  -- Sum of f(v, u). This requires iterating over all nodes v that have edge to u.
  -- We can iterate over all nodes v from 0 to size-1.
  -- This is a bit computationally heavy for definition but fine for spec.
  (List.range g.size).foldl (λ sum v => sum + f.get v u) 0

def is_conserved (g : CapacityGraph) (f : FlowMap) (s t : Nat) : Prop :=
  ∀ u, u < g.size → u ≠ s → u ≠ t →
    flow_in g f u = flow_out g f u

def is_valid_flow (g : CapacityGraph) (f : FlowMap) (s t : Nat) : Prop :=
  g.respects_capacity f ∧ is_conserved g f s t

def flow_val (g : CapacityGraph) (f : FlowMap) (s : Nat) : Int :=
  flow_out g f s - flow_in g f s

def is_max_flow (g : CapacityGraph) (f : FlowMap) (s t : Nat) : Prop :=
  is_valid_flow g f s t ∧
  ∀ other, is_valid_flow g other s t → flow_val g f s ≥ flow_val g other s

def CapacityGraph.capacities_bounded (g : CapacityGraph) : Prop :=
  g.size ≤ 1000 ∧
  ∀ u v c, g.has_capacity u v c → c ≥ 0 ∧ c ≤ 100000

-- Precondition definitions
@[reducible, simp]
def max_flow_value_precond (graph : CapacityGraph) (s t : Nat) : Prop :=
  -- !benchmark @start precond
  graph.well_formed ∧
  graph.capacities_bounded ∧
  s < graph.size ∧
  t < graph.size ∧
  s ≠ t
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def max_flow_value (graph : CapacityGraph) (s t : Nat)
    (h_precond : max_flow_value_precond graph s t) : Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def max_flow_value_postcond (graph : CapacityGraph) (s t : Nat) (result : Int)
    (_ : max_flow_value_precond graph s t) : Prop :=
  -- !benchmark @start postcond
  ∃ f, is_max_flow graph f s t ∧ flow_val graph f s = result
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem max_flow_value_postcond_satisfied (graph : CapacityGraph) (s t : Nat)
    (h_precond : max_flow_value_precond graph s t) :
    max_flow_value_postcond graph s t (max_flow_value graph s t h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement a Queue and verify its First-In, First-Out correctness in Lean. The queue is modeled as a sequence. You should implement and verify the dequeue operation. Dequeue: Verify that the operation returns the first element (index 0) of the sequence and that the new model sequence contains all remaining elements in their original relative order (the tail of the list). In a functional setting, the function should accept a proof of non-emptiness and return both the dequeued value and the new queue state.

import Mathlib

structure VerifiableQueue (T : Type) where
  data : List T

def VerifiableQueue.view {T} (q : VerifiableQueue T) : List T :=
  q.data

def VerifiableQueue.is_valid {T} (q : VerifiableQueue T) : Prop :=
  True

-- Precondition definitions
@[reducible, simp]
def dequeue_precond {T} (q : VerifiableQueue T) : Prop :=
  -- !benchmark @start precond
  q.is_valid ∧ q.view.length > 0
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
-- Returns the projected pair (val, new_queue)
def dequeue {T} (q : VerifiableQueue T)
    (h_precond : dequeue_precond q) : T × VerifiableQueue T :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def dequeue_postcond {T} (q : VerifiableQueue T) (result : T × VerifiableQueue T)
    (_ : dequeue_precond q) : Prop :=
  -- !benchmark @start postcond
  let (val, new_queue) := result
  new_queue.is_valid ∧
  -- Concise & Proof-Free: The old queue consists of the return value followed by the new queue.
  q.view = val :: new_queue.view
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem dequeue_postcond_satisfied {T} (q : VerifiableQueue T)
    (h_precond : dequeue_precond q) :
    dequeue_postcond q (dequeue q h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement a Queue and verify its First-In, First-Out correctness in Lean. The queue is modeled as a sequence where elements enter at the "back" and exit from the "front." You should implement and verify the enqueue (push) operation. Enqueue: Verify that the item is appended to the end of the model sequence. In a functional setting, this means returning a new queue with the item appended to the data list.

import Mathlib

structure VerifiableQueue (T : Type) where
  data : List T

def VerifiableQueue.view {T} (q : VerifiableQueue T) : List T :=
  q.data

def VerifiableQueue.is_valid {T} (q : VerifiableQueue T) : Prop :=
  True

-- Precondition definitions
@[reducible, simp]
def enqueue_precond {T} (q : VerifiableQueue T) (v : T) : Prop :=
  -- !benchmark @start precond
  q.is_valid
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def enqueue {T} (q : VerifiableQueue T) (v : T)
    (h_precond : enqueue_precond q v) : VerifiableQueue T :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def enqueue_postcond {T} (q : VerifiableQueue T) (v : T) (result : VerifiableQueue T)
    (_ : enqueue_precond q v) : Prop :=
  -- !benchmark @start postcond
  result.is_valid ∧
  result.view = q.view ++ [v]
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem enqueue_postcond_satisfied {T} (q : VerifiableQueue T) (v : T)
    (h_precond : enqueue_precond q v) :
    enqueue_postcond q v (enqueue q v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Quick Sort algorithm and verify its correctness in Lean. Given a list of integers, return a new list containing the same elements sorted in non-decreasing order. Postconditions: (1) Output is sorted. (2) Output is a permutation of input. Preconditions: None. Implementation: Recursive divide-and-conquer. Pick a pivot (e.g., head), partition the remaining elements into those less-than-or-equal and those greater-than, then recursively sort and append. Use 'partial' or prove termination (decreasing size).

import Mathlib

-- Precondition definitions
@[reducible, simp]
def quickSort_precond (v : List Int) : Prop :=
  -- !benchmark @start precond
  True
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def quickSort (v : List Int) (h_precond : quickSort_precond v) : List Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def quickSort_postcond (v : List Int) (result : List Int) (h_precond : quickSort_precond v) : Prop :=
  -- !benchmark @start postcond
   List.Sorted (· ≤ ·) result ∧ result.Perm v
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem quickSort_postcond_satisfied (v : List Int) (h_precond : quickSort_precond v) :
    quickSort_postcond v (quickSort v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement and verify the dequeue operation for a Ring Buffer data structure in Lean. Because the ring buffer uses a fixed-size underlying array, the "front" of the queue is tracked by a head pointer. Verification: Verify that the operation returns the element currently at the "front" of the logical sequence (index 0). Structural Update: You must prove that after the element is returned, the new model view is shortened by one and contains the remaining elements in their original relative order (tail of the view). Capacity remains unchanged.

import Mathlib

structure RingBuffer (T : Type) where
  capacity : Nat
  view : List T

def RingBuffer.is_valid {T} (rb : RingBuffer T) : Prop :=
  rb.capacity > 0 ∧ rb.view.length ≤ rb.capacity

-- Precondition definitions
@[reducible, simp]
def dequeue_precond {T} (rb : RingBuffer T) : Prop :=
  -- !benchmark @start precond
  rb.is_valid ∧ rb.view.length > 0
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
-- Returns (value, new_ringbuffer)
def dequeue {T} (rb : RingBuffer T)
    (h_precond : dequeue_precond rb) : T × RingBuffer T :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def dequeue_postcond {T} (rb : RingBuffer T) (result : T × RingBuffer T)
    (_ : dequeue_precond rb) : Prop :=
  -- !benchmark @start postcond
  let (val, new_rb) := result
  new_rb.is_valid ∧
  new_rb.capacity = rb.capacity ∧
  -- Concise & Proof-Free: Old view is (val :: new_view)
  rb.view = val :: new_rb.view
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem dequeue_postcond_satisfied {T} (rb : RingBuffer T)
    (h_precond : dequeue_precond rb) :
    dequeue_postcond rb (dequeue rb h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement and verify the circular enqueue operation for a Ring Buffer in Lean. The ring buffer is modeled as a sequence with a fixed capacity. Enqueue: Verify that if the buffer is not full, the element is appended. If the buffer is full, the oldest element (head) is discarded, and the new element is appended, maintaining the fixed capacity (First-In, First-Out with Overwrite). In a functional setting, return a new Ring Buffer state.

import Mathlib

structure RingBuffer (T : Type) where
  capacity : Nat
  view : List T

def RingBuffer.is_valid {T} (rb : RingBuffer T) : Prop :=
  rb.capacity > 0 ∧ rb.view.length ≤ rb.capacity

-- Precondition definitions
@[reducible, simp]
def enqueue_precond {T} (rb : RingBuffer T) (v : T) : Prop :=
  -- !benchmark @start precond
  rb.is_valid
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def enqueue {T} (rb : RingBuffer T) (v : T)
    (h_precond : enqueue_precond rb v) : RingBuffer T :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def enqueue_postcond {T} (rb : RingBuffer T) (v : T) (result : RingBuffer T)
    (_ : enqueue_precond rb v) : Prop :=
  -- !benchmark @start postcond
  result.is_valid ∧
  result.capacity = rb.capacity ∧
  (rb.view.length < rb.capacity → result.view = rb.view ++ [v]) ∧
  (rb.view.length = rb.capacity → result.view = rb.view.drop 1 ++ [v])
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem enqueue_postcond_satisfied {T} (rb : RingBuffer T) (v : T)
    (h_precond : enqueue_precond rb v) :
    enqueue_postcond rb v (enqueue rb v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Rod Cutting algorithm and verify its correctness in Lean. Given a rod of length n and a table of prices (where prices[i] is the price of a piece of length i+1), determine the maximum revenue obtainable by cutting the rod given the prices. Postconditions: Upper Bound (result ≥ revenue of any valid cut strategy) and Existence (result = revenue of some valid cut strategy). Valid strategy means cut lengths sum to n.

import Mathlib

def sum_lengths (cuts : List Nat) : Nat :=
  cuts.foldl (· + ·) 0

def get_price (prices : List Nat) (len : Nat) : Nat :=
  if len > 0 then prices.getD (len - 1) 0 else 0

def calculate_revenue (cuts : List Nat) (prices : List Nat) : Nat :=
  cuts.foldl (fun acc len => acc + get_price prices len) 0

def is_valid_strategy (cuts : List Nat) (n : Nat) (prices : List Nat) : Prop :=
  (∀ len ∈ cuts, len > 0 ∧ len - 1 < prices.length) ∧
  sum_lengths cuts = n

-- Precondition definitions
@[reducible, simp]
def rod_cutting_precond (n : Nat) (prices : List Nat) : Prop :=
  -- !benchmark @start precond
  prices.length ≥ n ∧
  n ≤ 1000 ∧
  (∀ i, i < prices.length → prices.getD i 0 ≤ 10000)
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def rod_cutting (n : Nat) (prices : List Nat)
    (h_precond : rod_cutting_precond n prices) : Nat :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def rod_cutting_postcond (n : Nat) (prices : List Nat) (result : Nat)
    (_ : rod_cutting_precond n prices) : Prop :=
  -- !benchmark @start postcond
  (∀ cuts, is_valid_strategy cuts n prices → calculate_revenue cuts prices ≤ result) ∧
  (∃ cuts, is_valid_strategy cuts n prices ∧ calculate_revenue cuts prices = result)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem rod_cutting_postcond_satisfied (n : Nat) (prices : List Nat)
    (h_precond : rod_cutting_precond n prices) :
    rod_cutting_postcond n prices (rod_cutting n prices h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement Tarjan's Algorithm to find the Strongly Connected Components (SCCs) of a directed graph and verify its functional correctness in Lean using Mathlib. Preconditions: You can assume the graph contains at most 1,000 nodes. The graph is directed and represented as an adjacency list. Requirements: Implement the function find_sccs which returns a List (List Nat). Output Format: The result must be a list of lists, where each inner list represents one Strongly Connected Component. Partition: The set of returned components must form a partition of the graph vertices. Strong Connectivity: For every component returned, and for every pair of nodes $(u, v)$ within that component, there must exist a path $u \rightsquigarrow v$ AND a path $v \rightsquigarrow u$. Maximality: The components must be maximal. This means no two components can be merged to form a larger strongly connected set. Formally, if there is a path from Component A to Component B, there must be no path from Component B back to Component A (The "Condensation Graph" must be a DAG). Verification Challenges: (1) DFS Invariants: Tarjan's algorithm uses discovery_time and low_link values. You must prove that low_link[u] correctly identifies the highest ancestor reachable from u in the DFS tree. (2) Stack Property: You must prove that the stack used during DFS correctly tracks the current path and potential "open" SCCs. (3) Maximality Proof: Proving that the algorithm does not "break" a large component into smaller valid pieces.

import Mathlib

structure SCCGraph where
  adj : Array (Array Nat)

def SCCGraph.well_formed (g : SCCGraph) : Prop :=
  ∀ u, u < g.adj.size →
    ∀ v, v ∈ g.adj.getD u #[] → v < g.adj.size

def SCCGraph.size (g : SCCGraph) : Nat :=
  g.adj.size

def SCCGraph.has_edge (g : SCCGraph) (u v : Nat) : Prop :=
  u < g.adj.size ∧
  v ∈ g.adj.getD u #[]

def SCCGraph.is_path (g : SCCGraph) (p : List Nat) : Prop :=
  p.length > 0 ∧
  ∀ i, i + 1 < p.length →
    g.has_edge (p.getD i 0) (p.getD (i + 1) 0)

def SCCGraph.has_path (g : SCCGraph) (u v : Nat) : Prop :=
  ∃ p, g.is_path p ∧ p.head? = some u ∧ p.getLast? = some v

def SCCGraph.is_strongly_connected (g : SCCGraph) (comp : List Nat) : Prop :=
  comp.length > 0 ∧
  (∀ u, u ∈ comp → u < g.size) ∧
  ∀ u v, u ∈ comp → v ∈ comp →
    (g.has_path u v ∧ g.has_path v u)

def SCCGraph.is_partition (g : SCCGraph) (sccs : List (List Nat)) : Prop :=
  -- Enforce no duplicate components to match index-based disjointness
  sccs.Nodup ∧
  -- All nodes covered
  (∀ u, u < g.size → ∃ comp, comp ∈ sccs ∧ u ∈ comp) ∧
  -- Disjoint
  (∀ c1 c2, c1 ∈ sccs → c2 ∈ sccs → c1 ≠ c2 →
    ∀ u, u ∈ c1 → u ∉ c2)

def SCCGraph.scc_has_path (g : SCCGraph) (c1 c2 : List Nat) : Prop :=
  ∃ u v, u ∈ c1 ∧ v ∈ c2 ∧ g.has_path u v

def SCCGraph.is_maximal_scc_structure (g : SCCGraph) (sccs : List (List Nat)) : Prop :=
  ∀ c1 c2, c1 ∈ sccs → c2 ∈ sccs → c1 ≠ c2 →
    (g.scc_has_path c1 c2 → ¬ g.scc_has_path c2 c1)

def SCCGraph.is_valid_scc_result (g : SCCGraph) (sccs : List (List Nat)) : Prop :=
  g.is_partition sccs ∧
  (∀ c, c ∈ sccs → g.is_strongly_connected c) ∧
  g.is_maximal_scc_structure sccs

-- Precondition definitions
@[reducible, simp]
def find_sccs_precond (graph : SCCGraph) : Prop :=
  -- !benchmark @start precond
  graph.well_formed ∧ graph.size ≤ 1000
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def find_sccs (graph : SCCGraph)
    (h_precond : find_sccs_precond graph) : List (List Nat) :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def find_sccs_postcond (graph : SCCGraph) (result : List (List Nat))
    (_ : find_sccs_precond graph) : Prop :=
  -- !benchmark @start postcond
  graph.is_valid_scc_result result
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem find_sccs_postcond_satisfied (graph : SCCGraph)
    (h_precond : find_sccs_precond graph) :
    find_sccs_postcond graph (find_sccs graph h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the build operation for a Range Maximum Segment Tree and verify its correctness in Lean. The operation builds a tree for range [l, r) initialized to 0. Postconditions: Result is a valid Segment Tree, covers range [l, r), and all values in view are 0. Invariants: Node value is max of children, ranges match children ranges.

import Mathlib

inductive Node
| mk (val : Int) (low high : Int) (left right : Option Node)
deriving Inhabited

namespace Node

def val (t : Node) : Int :=
  match t with | Node.mk v _ _ _ _ => v

def low (t : Node) : Int :=
  match t with | Node.mk _ l _ _ _ => l

def high (t : Node) : Int :=
  match t with | Node.mk _ _ h _ _ => h

def left (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ l _ => l

def right (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ _ r => r

end Node

def view (t : Node) : Int → Option Int :=
  fun k =>
    if k < t.low ∨ k ≥ t.high then none
    else
      match t.left, t.right with
      | some l, some r =>
          if k < l.high then view l k else view r k
      | _, _ => some t.val
termination_by sizeOf t
decreasing_by all_goals sorry

def is_segment_tree (t : Node) : Prop :=
  0 ≤ t.low ∧ t.low < t.high ∧ 0 ≤ t.val ∧
  match t.left, t.right with
  | some l, some r =>
      let mid := (t.low + t.high) / 2
      l.low = t.low ∧ l.high = mid ∧
      r.low = mid ∧ r.high = t.high ∧
      is_segment_tree l ∧ is_segment_tree r ∧
      t.val = max l.val r.val
  | none, none =>
      t.high = t.low + 1
  | _, _ => False
termination_by sizeOf t
decreasing_by all_goals sorry

-- Precondition definitions
@[reducible, simp]
def build_precond (l r : Int) : Prop :=
  -- !benchmark @start precond
  0 ≤ l ∧ l < r
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def build (l r : Int)
    (h_precond : build_precond l r) : Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Abstract View Helper used in Postcond
def tree_view_at (t : Node) (k : Int) : Int :=
  match view t k with
  | some v => v
  | none => 0 -- Should not happen for in-range queries if consistent

-- Postcondition definitions
@[reducible, simp]
def build_postcond (l r : Int) (result : Node)
    (_ : build_precond l r) : Prop :=
  -- !benchmark @start postcond
  is_segment_tree result ∧
  result.low = l ∧
  result.high = r ∧
  (∀ k, l ≤ k ∧ k < r → tree_view_at result k = 0)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem build_postcond_satisfied (l r : Int)
    (h_precond : build_precond l r) :
    build_postcond l r (build l r h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the update (modify) operation for a Range Maximum Segment Tree and verify its correctness in Lean. The operation updates the value at a specific index using path copying (functional update). Postconditions: Functional Correctness (view(result) = view(node)[idx := v]) and Invariant Preservation (result satisfies is_segment_tree). Frame Preservation (other indices unchanged).

import Mathlib

inductive Node
| mk (val : Int) (low high : Int) (left right : Option Node)
deriving Inhabited

namespace Node

def val (t : Node) : Int :=
  match t with | Node.mk v _ _ _ _ => v

def low (t : Node) : Int :=
  match t with | Node.mk _ l _ _ _ => l

def high (t : Node) : Int :=
  match t with | Node.mk _ _ h _ _ => h

def left (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ l _ => l

def right (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ _ r => r

end Node

def view (t : Node) : Int → Option Int :=
  fun k =>
    if k < t.low ∨ k ≥ t.high then none
    else
      match t.left, t.right with
      | some l, some r =>
          if k < l.high then view l k else view r k
      | _, _ => some t.val
termination_by sizeOf t
decreasing_by all_goals sorry

def is_segment_tree (t : Node) : Prop :=
  0 ≤ t.low ∧ t.low < t.high ∧ 0 ≤ t.val ∧
  match t.left, t.right with
  | some l, some r =>
      let mid := (t.low + t.high) / 2
      l.low = t.low ∧ l.high = mid ∧
      r.low = mid ∧ r.high = t.high ∧
      is_segment_tree l ∧ is_segment_tree r ∧
      t.val = max l.val r.val
  | none, none =>
      t.high = t.low + 1
  | _, _ => False
termination_by sizeOf t
decreasing_by all_goals sorry

-- Precondition definitions
@[reducible, simp]
def modify_precond (node : Node) (idx : Int) (v : Int) : Prop :=
  -- !benchmark @start precond
  0 ≤ v ∧
  is_segment_tree node ∧
  node.low ≤ idx ∧ idx < node.high
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def updateTree (node : Node) (idx : Int) (v : Int)
    (h_precond : modify_precond node idx v) : Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Abstract View Helper used in Postcond
def tree_view_at (t : Node) (k : Int) : Int :=
  match view t k with
  | some v => v
  | none => 0

-- Postcondition definitions
@[reducible, simp]
def modify_postcond (node : Node) (idx : Int) (v : Int) (result : Node)
    (_ : modify_precond node idx v) : Prop :=
  -- !benchmark @start postcond
  is_segment_tree result ∧
  result.low = node.low ∧
  result.high = node.high ∧
  (∀ k, node.low ≤ k ∧ k < node.high →
      if k = idx then tree_view_at result k = v
      else tree_view_at result k = tree_view_at node k)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem modify_postcond_satisfied (node : Node) (idx : Int) (v : Int)
    (h_precond : modify_precond node idx v) :
    modify_postcond node idx v (updateTree node idx v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the query operation for a Range Maximum Segment Tree and verify its correctness in Lean. The operation queries the maximum value in range [ql, qr). Postconditions: Correctness (result ≥ all values in range), Tightness (result exists in range). Invariant: Node is a valid segment tree.

import Mathlib

inductive Node
| mk (val : Int) (low high : Int) (left right : Option Node)
deriving Inhabited

namespace Node

def val (t : Node) : Int :=
  match t with | Node.mk v _ _ _ _ => v

def low (t : Node) : Int :=
  match t with | Node.mk _ l _ _ _ => l

def high (t : Node) : Int :=
  match t with | Node.mk _ _ h _ _ => h

def left (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ l _ => l

def right (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ _ r => r

end Node

def view (t : Node) : Int → Option Int :=
  fun k =>
    if k < t.low ∨ k ≥ t.high then none
    else
      match t.left, t.right with
      | some l, some r =>
          if k < l.high then view l k else view r k
      | _, _ => some t.val
termination_by sizeOf t
decreasing_by all_goals sorry

def is_segment_tree (t : Node) : Prop :=
  0 ≤ t.low ∧ t.low < t.high ∧ 0 ≤ t.val ∧
  match t.left, t.right with
  | some l, some r =>
      let mid := (t.low + t.high) / 2
      l.low = t.low ∧ l.high = mid ∧
      r.low = mid ∧ r.high = t.high ∧
      is_segment_tree l ∧ is_segment_tree r ∧
      t.val = max l.val r.val
  | none, none =>
      t.high = t.low + 1
  | _, _ => False
termination_by sizeOf t
decreasing_by all_goals sorry

-- Precondition definitions
@[reducible, simp]
def query_precond (node : Node) (ql qr : Int) : Prop :=
  -- !benchmark @start precond
  is_segment_tree node ∧
  ql < qr ∧
  node.low ≤ ql ∧
  qr ≤ node.high
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def query (node : Node) (ql qr : Int)
    (h_precond : query_precond node ql qr) : Int :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Abstract View Helper used in Postcond
def tree_view_at (t : Node) (k : Int) : Int :=
  match view t k with
  | some v => v
  | none => 0

-- Postcondition definitions
@[reducible, simp]
def query_postcond (node : Node) (ql qr : Int) (result : Int)
    (_ : query_precond node ql qr) : Prop :=
  -- !benchmark @start postcond
  result ≥ 0 ∧
  (∀ k, ql ≤ k ∧ k < qr → tree_view_at node k ≤ result) ∧
  (∃ k, ql ≤ k ∧ k < qr ∧ tree_view_at node k = result)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem query_postcond_satisfied (node : Node) (ql qr : Int)
    (h_precond : query_precond node ql qr) :
    query_postcond node ql qr (query node ql qr h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the classic Sieve of Eratosthenes algorithm to find all prime numbers up to a limit n and verify its correctness in Lean. Given a non-negative integer n, return a boolean array of size n where the i-th element is true iff i is prime. Preconditions: The input n is a natural number (Nat). You may assume n <= 100,000. Requirements: Implement the function `sieve_of_eratosthenes` which returns an `Array Bool`. (1) Output Format: The returned array must be of size n. For any index i, result[i] should be true if i is prime, and false otherwise. (2) Algorithm: Initialize a boolean array to true. Iterate i from 2 up to sqrt(n). If i is prime, iterate j starting from i*i up to n with a step size of i (j += i), marking these indices as false. Verification Challenges: (1) Array Invariants: You must maintain an invariant over the entire array. For example: "For all k < n, if arr[k] is true, then k has no prime factors smaller than the current loop index i". (2) Inner Loop Stride: The inner loop increments by i. You must prove that every index j visited by this loop is indeed a multiple of i. (3) Optimization Logic (i*i): The standard Sieve starts marking multiples from i*i. To verify this is safe, you must prove the lemma that any composite number x < i*i must have a prime factor strictly smaller than i.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def sieve_of_eratosthenes_precond (n : Nat) : Prop :=
  -- !benchmark @start precond
  n ≤ 100_000
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def sieve_of_eratosthenes (n : Nat) (h_precond : sieve_of_eratosthenes_precond n) : Array Bool :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def sieve_of_eratosthenes_postcond (n : Nat) (result : Array Bool) (h_precond : sieve_of_eratosthenes_precond n) : Prop :=
  -- !benchmark @start postcond
  result.size = n ∧
  ∀ i : Nat, i < n →
    ((result.getD i false = true) ↔
      (i > 1 ∧ ∀ d : Nat, (1 < d ∧ d < i) → i % d ≠ 0))
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem sieve_of_eratosthenes_postcond_satisfied (n : Nat) (h_precond : sieve_of_eratosthenes_precond n) :
    sieve_of_eratosthenes_postcond n (sieve_of_eratosthenes n h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Splay operation in a splay tree and verify its correctness in Lean. Splaying moves a target node (or the last accessed node) to the root via rotations (Zig, Zig-Zig, Zig-Zag). Postconditions: Result is BST, set of values is unchanged, and if v is in the tree, result.val = v.

import Mathlib

inductive SplayTree
| empty
| node (val : Int) (left right : SplayTree)
deriving Inhabited

namespace SplayTree

def view (t : SplayTree) : Set Int :=
  match t with
  | empty => ∅
  | node v l r => view l ∪ view r ∪ {v}
termination_by sizeOf t

def is_bst (t : SplayTree) : Prop :=
  match t with
  | empty => True
  | node v l r =>
    (∀ x ∈ view l, x < v) ∧
    is_bst l ∧
    (∀ x ∈ view r, x > v) ∧
    is_bst r
termination_by sizeOf t
decreasing_by all_goals sorry

def val (t : SplayTree) : Option Int :=
  match t with | node v _ _ => some v | empty => none

def is_node (t : SplayTree) : Bool :=
  match t with | node _ _ _ => true | empty => false

-- Precondition definitions
@[reducible, simp]
def splay_precond (t : SplayTree) (v : Int) : Prop :=
  -- !benchmark @start precond
  t.is_node ∧ is_bst t
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def splay (t : SplayTree) (v : Int)
    (h_precond : splay_precond t v) : SplayTree :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def splay_postcond (t : SplayTree) (v : Int) (result : SplayTree)
    (_ : splay_precond t v) : Prop :=
  -- !benchmark @start postcond
  result.is_node ∧
  is_bst result ∧
  view result = view t ∧
  (v ∈ view t → result.val = some v)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem splay_postcond_satisfied (t : SplayTree) (v : Int)
    (h_precond : splay_precond t v) :
    splay_postcond t v (splay t v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof

end SplayTree


Your task is to implement a Stack data structure and verify its Last-In, First-Out behavior in Lean. The stack is modeled as a mathematical sequence. Specifically, you are required to implement and verify the pop operation. Pop: You must prove that the operation returns the last element of the sequence and that the resulting model sequence is the original sequence minus its last element. You must also verify the safety precondition that the stack is non-empty before a pop. In a functional setting, the function should accept a proof of non-emptiness and return both the popped value and the new stack state.

import Mathlib

structure VerifiableStack (T : Type) where
  data : List T

def VerifiableStack.view {T} (s : VerifiableStack T) : List T :=
  s.data

def VerifiableStack.is_valid {T} (s : VerifiableStack T) : Prop :=
  True

-- Precondition definitions
@[reducible, simp]
def pop_precond {T} (s : VerifiableStack T) : Prop :=
  -- !benchmark @start precond
  s.is_valid ∧ s.view.length > 0
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
-- Returns the projected pair (val, new_stack)
def pop {T} (s : VerifiableStack T)
    (h_precond : pop_precond s) : T × VerifiableStack T :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def pop_postcond {T} (s : VerifiableStack T) (result : T × VerifiableStack T)
    (_ : pop_precond s) : Prop := -- We don't even need the proof term 'h' here!
  -- !benchmark @start postcond
  let (val, new_stack) := result
  new_stack.is_valid ∧
  -- Concise & Idiomatic: The old stack was the new stack followed by the popped value.
  s.view = new_stack.view ++ [val]
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem pop_postcond_satisfied {T} (s : VerifiableStack T)
    (h_precond : pop_precond s) :
    pop_postcond s (pop s h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement a Stack data structure and verify its Last-In, First-Out behavior in Lean. The stack is modeled as a mathematical sequence where elements are added and removed from the "top" (the end of the sequence). Specifically, you are required to implement and verify the push operation. Push: You must prove that after pushing an element, the new model sequence is equal to the old sequence with the new element appended to the end. In a functional setting, this means the function returns a new stack whose view is the old view with the element appended.

import Mathlib

structure VerifiableStack (T : Type) where
  data : List T

def VerifiableStack.view {T} (s : VerifiableStack T) : List T :=
  s.data

def VerifiableStack.is_valid {T} (s : VerifiableStack T) : Prop :=
  True

-- Precondition definitions
@[reducible, simp]
def push_precond {T} (s : VerifiableStack T) (v : T) : Prop :=
  -- !benchmark @start precond
  s.is_valid
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def push {T} (s : VerifiableStack T) (v : T)
    (h_precond : push_precond s v) : VerifiableStack T :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def push_postcond {T} (s : VerifiableStack T) (v : T) (result : VerifiableStack T)
    (_ : push_precond s v) : Prop :=
  -- !benchmark @start postcond
  result.is_valid ∧
  result.view = s.view ++ [v]
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem push_postcond_satisfied {T} (s : VerifiableStack T) (v : T)
    (h_precond : push_precond s v) :
    push_postcond s v (push s v h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement a Naive String Search algorithm to find all occurrences of a needle (pattern) within a haystack (text) and verify its functional correctness in Lean using Mathlib. Preconditions: You can assume the input text and pattern are arrays of UInt8 (representing bytes) and their lengths are at most 1,000,000. Requirements: Implement the method naive_search which returns an Array Nat containing all starting indices. (1) The method must iterate through every possible starting position in the haystack. (2) For each position, it must perform a character-by-character comparison to check for a match. (3) Soundness & Completeness: You must prove that every index returned is a valid match and that no valid match is omitted. Verification Challenges: (1) Nested Loop Invariants: You must correctly specify the invariant for the inner comparison loop to prove it correctly identifies a match or mismatch. (2) Quantifier Instantiation: Proving completeness involves complex quantifiers (forall indices, if a match exists, it is in the result), which may require manual triggers or ghost code to show the iteration covers the entire search space.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def naive_search_precond (haystack : Array UInt8) (needle : Array UInt8) : Prop :=
  -- !benchmark @start precond
  haystack.size < 1000000 ∧
  needle.size < 1000000
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def naive_search (haystack : Array UInt8) (needle : Array UInt8)
    (_ : naive_search_precond haystack needle) : Array Nat :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition auxiliary definitions
def matches_at (haystack needle : Array UInt8) (i : Nat) : Prop :=
  i + needle.size ≤ haystack.size ∧
  (∀ j, j < needle.size → haystack.getD (i + j) 0 = needle.getD j 0)

-- Postcondition definitions
@[reducible, simp]
def naive_search_postcond (haystack : Array UInt8) (needle : Array UInt8)
    (result : Array Nat) (_ : naive_search_precond haystack needle) : Prop :=
  -- !benchmark @start postcond
  (∀ i, i < result.size → matches_at haystack needle (result.getD i 0)) ∧
  (∀ i, matches_at haystack needle i → ∃ k, k < result.size ∧ result.getD k 0 = i)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem naive_search_postcond_satisfied (haystack : Array UInt8) (needle : Array UInt8)
    (h_precond : naive_search_precond haystack needle) :
    naive_search_postcond haystack needle (naive_search haystack needle h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Delete operation for a Ternary Search Tree (TST) and verify its correctness in Lean. The operation removes a key and performs "Eager Pruning" to remove useless nodes (nodes that are not endpoints and have no children). Postconditions: Functional Correctness (view(result) = view(tree) - {key}) and Invariant Preservation (result satisfies well-formedness).

import Mathlib

inductive Node
| mk (val : Int) (is_end : Bool) (left mid right : Option Node)
deriving Inhabited

namespace Node

def val (t : Node) : Int :=
  match t with | Node.mk v _ _ _ _ => v

def is_end (t : Node) : Bool :=
  match t with | Node.mk _ b _ _ _ => b

def left (t : Node) : Option Node :=
  match t with | Node.mk _ _ l _ _ => l

def mid (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ m _ => m

def right (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ _ r => r

end Node

def view (t : Node) : Set (List Int) :=
  let l := match t.left with | some child => view child | none => ∅
  let r := match t.right with | some child => view child | none => ∅
  let m := match t.mid with | some child => (view child).image (fun s => t.val :: s) | none => ∅
  let current := if t.is_end then {[t.val]} else ∅
  l ∪ r ∪ m ∪ current
termination_by sizeOf t
decreasing_by all_goals sorry

def is_empty_node (t : Node) : Bool :=
  !t.is_end ∧ t.left.isNone ∧ t.mid.isNone ∧ t.right.isNone

def well_formed (t : Node) : Prop :=
  (0 ≤ t.val ∧ t.val < 256) ∧
  -- Check Left
  (match t.left with
   | some l =>
       well_formed l ∧
       !is_empty_node l ∧ -- CRITICAL: Match Dafny pruning
       (∀ s ∈ view l, match s with | [] => False | c::_ => c < t.val)
   | none => True) ∧
  -- Check Right
  (match t.right with
   | some r =>
       well_formed r ∧
       !is_empty_node r ∧ -- CRITICAL
       (∀ s ∈ view r, match s with | [] => False | c::_ => c > t.val)
   | none => True) ∧
  -- Check Mid
  (match t.mid with
   | some m =>
       well_formed m ∧
       !is_empty_node m -- CRITICAL
   | none => True)
termination_by sizeOf t
decreasing_by all_goals sorry

def is_valid_key (key : List Int) : Prop :=
  ∀ k ∈ key, 0 ≤ k ∧ k < 256

-- Precondition definitions
@[reducible, simp]
def delete_precond (t : Option Node) (key : List Int) : Prop :=
  -- !benchmark @start precond
  (match t with
   | some node => well_formed node ∧ !is_empty_node node
   | none => True) ∧
  is_valid_key key -- Match Dafny input constraint
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def delete (t : Option Node) (key : List Int)
    (h_precond : delete_precond t key) : Option Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- View wrapper for Option Node
def view_opt (t : Option Node) : Set (List Int) :=
  match t with
  | some node => view node
  | none => ∅

-- Postcondition definitions
@[reducible, simp]
def delete_postcond (t : Option Node) (key : List Int) (result : Option Node)
    (_ : delete_precond t key) : Prop :=
  -- !benchmark @start postcond
  (match result with
   | some res => well_formed res ∧ !is_empty_node res
   | none => True) ∧
  view_opt result = view_opt t \ {key}
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem delete_postcond_satisfied (t : Option Node) (key : List Int)
    (h_precond : delete_precond t key) :
    delete_postcond t key (delete t key h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Insert operation for a Ternary Search Tree (TST) and verify its correctness in Lean. Postconditions: Functional Correctness (view(result) = view(tree) + {key}) and Invariant Preservation (result satisfies well-formedness). Insertion combines BST insertion (left/right) with Trie extension (mid). If path doesn't exist, create new chain.

import Mathlib

inductive Node
| mk (val : Int) (is_end : Bool) (left mid right : Option Node)
deriving Inhabited

namespace Node

def val (t : Node) : Int :=
  match t with | Node.mk v _ _ _ _ => v

def is_end (t : Node) : Bool :=
  match t with | Node.mk _ b _ _ _ => b

def left (t : Node) : Option Node :=
  match t with | Node.mk _ _ l _ _ => l

def mid (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ m _ => m

def right (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ _ r => r

end Node

def view (t : Node) : Set (List Int) :=
  let l := match t.left with | some child => view child | none => ∅
  let r := match t.right with | some child => view child | none => ∅
  let m := match t.mid with | some child => (view child).image (fun s => t.val :: s) | none => ∅
  let current := if t.is_end then {[t.val]} else ∅
  l ∪ r ∪ m ∪ current
termination_by sizeOf t
decreasing_by all_goals sorry

def is_empty_node (t : Node) : Bool :=
  !t.is_end ∧ t.left.isNone ∧ t.mid.isNone ∧ t.right.isNone

def well_formed (t : Node) : Prop :=
  (0 ≤ t.val ∧ t.val < 256) ∧
  -- Check Left
  (match t.left with
   | some l =>
       well_formed l ∧
       !is_empty_node l ∧ -- CRITICAL: Match Dafny pruning
       (∀ s ∈ view l, match s with | [] => False | c::_ => c < t.val)
   | none => True) ∧
  -- Check Right
  (match t.right with
   | some r =>
       well_formed r ∧
       !is_empty_node r ∧ -- CRITICAL
       (∀ s ∈ view r, match s with | [] => False | c::_ => c > t.val)
   | none => True) ∧
  -- Check Mid
  (match t.mid with
   | some m =>
       well_formed m ∧
       !is_empty_node m -- CRITICAL
   | none => True)
termination_by sizeOf t
decreasing_by all_goals sorry

def is_valid_key (key : List Int) : Prop :=
  ∀ k ∈ key, 0 ≤ k ∧ k < 256

-- Precondition definitions
@[reducible, simp]
def insert_precond (t : Option Node) (key : List Int) : Prop :=
  -- !benchmark @start precond
  (match t with
   | some node => well_formed node ∧ !is_empty_node node
   | none => True) ∧
  is_valid_key key ∧ -- Match Dafny byte constraint
  key.length > 0     -- Match Dafny non-empty constraint
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def insert (t : Option Node) (key : List Int)
    (h_precond : insert_precond t key) : Node :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- View wrapper for Option Node
def view_opt (t : Option Node) : Set (List Int) :=
  match t with
  | some node => view node
  | none => ∅

-- Postcondition definitions
@[reducible, simp]
def insert_postcond (t : Option Node) (key : List Int) (result : Node)
    (_ : insert_precond t key) : Prop :=
  -- !benchmark @start postcond
  well_formed result ∧
  !is_empty_node result ∧
  view result = view_opt t ∪ {key}
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem insert_postcond_satisfied (t : Option Node) (key : List Int)
    (h_precond : insert_precond t key) :
    insert_postcond t key (insert t key h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the Search operation for a Ternary Search Tree (TST) and verify its correctness in Lean. A TST Node has a value (val), an end marker (is_end), and three children: left (val > char), mid (val == char), right (val < char). Postconditions: Functional Correctness (view(result) = view(tree) contains key). Preconditions: Input assumed well-formed. Search logic respects 3-way branching.

import Mathlib

inductive Node
| mk (val : Int) (is_end : Bool) (left mid right : Option Node)
deriving Inhabited

namespace Node

def val (t : Node) : Int :=
  match t with | Node.mk v _ _ _ _ => v

def is_end (t : Node) : Bool :=
  match t with | Node.mk _ b _ _ _ => b

def left (t : Node) : Option Node :=
  match t with | Node.mk _ _ l _ _ => l

def mid (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ m _ => m

def right (t : Node) : Option Node :=
  match t with | Node.mk _ _ _ _ r => r

end Node

def view (t : Node) : Set (List Int) :=
  let l := match t.left with | some child => view child | none => ∅
  let r := match t.right with | some child => view child | none => ∅
  let m := match t.mid with | some child => (view child).image (fun s => t.val :: s) | none => ∅
  let current := if t.is_end then {[t.val]} else ∅
  l ∪ r ∪ m ∪ current
termination_by sizeOf t
decreasing_by all_goals sorry

def is_empty_node (t : Node) : Bool :=
  !t.is_end ∧ t.left.isNone ∧ t.mid.isNone ∧ t.right.isNone

def well_formed (t : Node) : Prop :=
  (0 ≤ t.val ∧ t.val < 256) ∧
  -- Check Left
  (match t.left with
   | some l =>
       well_formed l ∧
       !is_empty_node l ∧ -- CRITICAL: Match Dafny pruning
       (∀ s ∈ view l, match s with | [] => False | c::_ => c < t.val)
   | none => True) ∧
  -- Check Right
  (match t.right with
   | some r =>
       well_formed r ∧
       !is_empty_node r ∧ -- CRITICAL
       (∀ s ∈ view r, match s with | [] => False | c::_ => c > t.val)
   | none => True) ∧
  -- Check Mid
  (match t.mid with
   | some m =>
       well_formed m ∧
       !is_empty_node m -- CRITICAL
   | none => True)
termination_by sizeOf t
decreasing_by all_goals sorry

def contains (t : Node) (key : List Int) : Bool :=
  match key with
  | [] => False -- TST nodes always represent at least one char
  | c :: cs =>
    if c < t.val then
      match t.left with | some l => contains l key | none => False
    else if c > t.val then
      match t.right with | some r => contains r key | none => False
    else -- c == t.val
      match cs with
      | [] => t.is_end
      | _ => match t.mid with | some m => contains m cs | none => False
termination_by sizeOf t
decreasing_by all_goals sorry

def is_valid_key (key : List Int) : Prop :=
  ∀ k ∈ key, 0 ≤ k ∧ k < 256

-- Precondition definitions
@[reducible, simp]
def search_precond (t : Option Node) (key : List Int) : Prop :=
  -- !benchmark @start precond
  (match t with
   | some node => well_formed node ∧ !is_empty_node node
   | none => True) ∧
  is_valid_key key -- Match Dafny input constraint
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def search (t : Option Node) (key : List Int)
    (h_precond : search_precond t key) : Bool :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- View wrapper for Option Node
def view_opt (t : Option Node) : Set (List Int) :=
  match t with
  | some node => view node
  | none => ∅

-- Postcondition definitions
@[reducible, simp]
def search_postcond (t : Option Node) (key : List Int) (result : Bool)
    (_ : search_precond t key) : Prop :=
  -- !benchmark @start postcond
  result = (key ∈ view_opt t)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem search_postcond_satisfied (t : Option Node) (key : List Int)
    (h_precond : search_precond t key) :
    search_postcond t key (search t key h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement a Topological Sort algorithm and verify its functional correctness in Lean using Mathlib. You need to implement topological_sort, which takes a directed graph and returns Some(order) containing a valid topological ordering if the graph is a DAG, or None if the graph contains a cycle. There are several verification challenges: (1) Ordering Validity: If returning Some(order), you must prove that order is a permutation of all graph nodes and that for every edge $u \to v$ in the graph, $u$ appears before $v$ in the sequence. (2) Cycle Detection: If returning None, you must prove that the graph actually contains a cycle. This ensures the algorithm doesn't fail spuriously on valid DAGs.

import Mathlib

structure TopoGraph where
  adj : Array (Array Nat)

def TopoGraph.well_formed (g : TopoGraph) : Prop :=
  ∀ u, u < g.adj.size →
    ∀ v, v ∈ g.adj.getD u #[] → v < g.adj.size

def TopoGraph.size (g : TopoGraph) : Nat :=
  g.adj.size

def TopoGraph.has_edge (g : TopoGraph) (u v : Nat) : Prop :=
  u < g.adj.size ∧
  v ∈ g.adj.getD u #[]

def TopoGraph.is_path (g : TopoGraph) (p : List Nat) : Prop :=
  p.length > 0 ∧
  ∀ i, i + 1 < p.length →
    g.has_edge (p.getD i 0) (p.getD (i + 1) 0)

def TopoGraph.is_cycle (g : TopoGraph) (p : List Nat) : Prop :=
  g.is_path p ∧ p.length > 1 ∧ p.head? = p.getLast?

def TopoGraph.graph_has_cycle (g : TopoGraph) : Prop :=
  ∃ p, g.is_cycle p

def TopoGraph.is_topological_ordering (g : TopoGraph) (order : Array Nat) : Prop :=
  -- Contains all nodes (size check + surjective)
  order.size = g.size ∧
  (∀ n, n < g.size → ∃ k, k < order.size ∧ order.getD k 0 = n) ∧
  -- No duplicates is implied by size check + surjective on finite set, but for completeness:
  (∀ i j, i < order.size → j < order.size → i ≠ j → order.getD i 0 ≠ order.getD j 0) ∧
  -- No back edges (if j < i, no edge order[i] -> order[j])
  (∀ i j, j < i → i < order.size →
     ¬ g.has_edge (order.getD i 0) (order.getD j 0))

-- Precondition definitions
@[reducible, simp]
def topological_sort_precond (graph : TopoGraph) : Prop :=
  -- !benchmark @start precond
  graph.well_formed
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definition
def topological_sort (graph : TopoGraph)
    (h_precond : topological_sort_precond graph) : Option (Array Nat) :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def topological_sort_postcond (graph : TopoGraph) (result : Option (Array Nat))
    (_ : topological_sort_precond graph) : Prop :=
  -- !benchmark @start postcond
  match result with
  | some order =>
      ¬ graph.graph_has_cycle ∧
      graph.is_topological_ordering order
  | none =>
      graph.graph_has_cycle
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem topological_sort_postcond_satisfied (graph : TopoGraph)
    (h_precond : topological_sort_precond graph) :
    topological_sort_postcond graph (topological_sort graph h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the "Trial Division (Naive)" Primality Test and verify its correctness in Lean. Preconditions: The input n is a natural number (Nat). Postconditions: Implement the function `check_prime` which returns true if n is prime and false otherwise. (1) Algorithm: You should use a simple trial division loop (or recursion) that checks every integer from 2 up to n - 1. (2) Functional Correctness: You must verify that your result matches the mathematical definition of primality (a number n > 1 divisible only by 1 and itself). Verification Challenges: (1) Loop Invariant: You must maintain an invariant stating that "for all k checked so far (2 <= k < i), k does not divide n". (2) Quantifier Instantiation: When the loop finishes without finding a divisor, you must prove that this implies the universal quantifier forall d. 1 < d < n -> n % d != 0.

import Mathlib

-- Precondition definitions
@[reducible, simp]
def check_prime_precond (n : Nat) : Prop :=
  -- !benchmark @start precond
  True
  -- !benchmark @end precond

-- !benchmark @start auxcode
-- !benchmark @end auxcode

-- Main function definitions
def check_prime (n : Nat) (h_precond : check_prime_precond n) : Bool :=
  -- !benchmark @start code
  sorry
  -- !benchmark @end code

-- Postcondition definitions
@[reducible, simp]
def check_prime_postcond (n : Nat) (result : Bool) (h_precond : check_prime_precond n) : Prop :=
  -- !benchmark @start postcond
  result = true ↔ (n > 1 ∧ ∀ d : Nat, 1 < d ∧ d < n → n % d ≠ 0)
  -- !benchmark @end postcond

-- !benchmark @start lemma
-- !benchmark @end lemma

-- Proof content
theorem check_prime_postcond_satisfied (n : Nat) (h_precond : check_prime_precond n) :
    check_prime_postcond n (check_prime n h_precond) h_precond := by
  -- !benchmark @start proof
  sorry
  -- !benchmark @end proof


Your task is to implement the "Optimized Trial Division" primality test algorithm and verify its functional correctness in Lean. Given a non-negative integer n, determine whether n is prime by dividing it by integers from 2 up to sqrt(n). Postconditions: Returns true iff n > 1 and has no divisors between 2 and n-1. Preconditions: n is a natural number (Nat). Verification Challenges: (1) Algorithm: Stop checking when i * i > n. (2) Proof Requirement: You must prove that if no divisor is found up to sqrt(n), then no divisor exists up to n-1. This requires stating and proving the number-theoretic lemma: if n is composite, it has a factor less than or equal to its square root.