import Mathlib.Tacticnamespace DecayEdgeRefinement/-- Slots assigned to a provisional color. The second coordinate numbers theallowed edges of an actual color starting at zero. -/def slots (pool : Finset ℕ) (cap : ℕ → ℕ) : Finset (Σ _ : ℕ, ℕ) :=pool.sigma fun i => Finset.range (cap i)theorem assign_one {α : Type*} [DecidableEq α] (s : Finset α) (pool : Finset ℕ)(cap : ℕ → ℕ) (enough : s.card ≤ ∑ i ∈ pool, cap i) :∃ f : α → ℕ × ℕ, Set.InjOn f (s : Set α) ∧∀ x ∈ s, (f x).1 ∈ pool ∧ (f x).2 < cap (f x).1 := byclassicalhave count : Fintype.card (↥s) ≤ Fintype.card (↥(slots pool cap)) := bysimpa [slots, Finset.card_sigma] using enoughlet emb := (Function.Embedding.nonempty_of_card_le count).somelet f (x : α) : ℕ × ℕ :=if h : x ∈ s then ((emb ⟨x,h⟩).val.1, (emb ⟨x,h⟩).val.2) else (0,0)refine ⟨f, ?_, ?_⟩· intro x hx y hy hxychange x ∈ s at hxchange y ∈ s at hyhave eqv : (emb ⟨x,hx⟩).val = (emb ⟨y,hy⟩).val := byhave hp := congrArg (fun v : ℕ × ℕ => (⟨v.1,v.2⟩ : Σ _ : ℕ, ℕ)) hxysimpa [f, hx, hy] using hpexact congrArg Subtype.val (emb.injective (Subtype.ext eqv))· intro x hxhave hm := Finset.mem_sigma.mp (emb ⟨x,hx⟩).propertysimpa [f, hx] using hm/-- Split a coloring of any finite edge set across disjoint palettes. Thisproduces actual color labels and proves every finite integer cap. -/theorem recolor {α : Type*} [DecidableEq α] (E : Finset α) (c : α → ℕ)(A : ℕ → Finset ℕ) (cap : ℕ → ℕ)(dis : ∀ j h, j ≠ h → Disjoint (A j) (A h))(enough : ∀ j, (E.filter (fun e => c e = j)).card ≤ ∑ i ∈ A j, cap i) :∃ c' : α → ℕ, (∀ e ∈ E, c' e ∈ A (c e)) ∧(∀ i, (E.filter (fun e => c' e = i)).card ≤ cap i) ∧∀ x ∈ E, ∀ y ∈ E, c' x = c' y → c x = c y := byclassicalchoose F hinj hmem usingfun j => assign_one (E.filter fun e => c e = j) (A j) cap (enough j)let pos (e : α) := F (c e) ehave hm : ∀ e ∈ E, (pos e).1 ∈ A (c e) ∧ (pos e).2 < cap (pos e).1 :=fun e he => hmem (c e) e (Finset.mem_filter.mpr ⟨he,rfl⟩)have parent : ∀ x ∈ E, ∀ y ∈ E, (pos x).1 = (pos y).1 → c x = c y := byintro x hx y hy hxyby_contra neexact Finset.disjoint_left.mp (dis _ _ ne) (hm x hx).1 (hxy ▸ (hm y hy).1)refine ⟨fun e => (pos e).1, fun e he => (hm e he).1, ?_, parent⟩intro icalc(E.filter (fun e => (pos e).1 = i)).card ≤ (Finset.range (cap i)).card := byapply Finset.card_le_card_of_injOn (fun e => (pos e).2)· intro e heobtain ⟨he, hi⟩ := Finset.mem_filter.mp heexact Finset.mem_range.mpr (hi ▸ (hm e he).2)· intro x hx y hy hxyobtain ⟨hx, hi⟩ := Finset.mem_filter.mp hxobtain ⟨hy, hj⟩ := Finset.mem_filter.mp hyhave heq := hi.trans hj.symmhave hc := parent x hx y hy heqhave both := Prod.ext heq hxychange F (c x) x = F (c y) y at bothrw [← hc] at bothexact hinj (c x) (Finset.mem_filter.mpr ⟨hx,rfl⟩)(Finset.mem_filter.mpr ⟨hy,hc.symm⟩) both_ = cap i := Finset.card_range _end DecayEdgeRefinement