/-
Copyright 2026 The Formal Conjectures Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/modulepublicimportMathlib.Combinatorics.SimpleGraph.FinitepublicimportMathlib.Data.Finset.Sort@[expose]publicsectionnamespaceSimpleGraphvariable{α:Type*}[Fintypeα][DecidableEqα]
Residue
The residue of a graph is the number of zeros remaining after iteratively applying the Havel-Hakimi
algorithm to the degree sequence until all remaining degrees are zero.
Helper function: Performs one step of the Havel-Hakimi reduction on a degree sequence.
Assumes the input list s is sorted descending.
Removes the first element d, decrements the next d elements by 1, and re-sorts the list descending.
Note: when s is the list of vertices arising from a simple graph, if the first index is s then
the degree list always has length at least s+1 so this makes sense.
defhavelHakimiStep(s:Listℕ):Listℕ:=matchswith|[]=>[]|d::rest=>-- Split the rest into the part to decrement (first d elements) and the remaining part.let(to_decrement,remaining):=rest.splitAtd-- Decrement the elementsletdecremented:=to_decrement.map(·-1)-- Combine and re-sort descending.(decremented++remaining).mergeSort(·≥·)
havelHakimiStep drops the list length by exactly one on a nonempty list:
(havelHakimiStep (d :: rest)).length = rest.length. splitAt partitions rest,
and map, ++, and mergeSort all preserve the total length while the head d
is dropped. This is the termination measure for the well-founded residueAux below.
Auxiliary function to calculate the residue recursively.
Applies Havel-Hakimi steps until the sequence consists only of zeros or is empty.
Defined by well-founded recursion on the list length (via havelHakimiStep_length_cons),
so that it admits equational and inductive reasoning.
Computes the residue of a graph G, i.e. the number of zeros remaining after iteratively
applying the Havel-Hakimi algorithm to the degree sequence until all remaining degrees are zero.
Starts with the descending degree sequence and applies the Havel-Hakimi process.
noncomputabledefresidue(G:SimpleGraphα)[DecidableRelG.Adj]:ℕ:=-- Get the degree sequence sorted in descending order and apply `residueAux`.residueAux((Finset.univ.val.mapfunv=>G.degreev).sort(·≥·))endSimpleGraph