Matrix-Tree Theorem

The matrix-tree theorem solves the problem of counting the number of spanning trees of a graph.

Notation in this article

The graphs in this article, whether undirected or directed, may have multiple edges, but are assumed to have no self-loops by default.

The case of self-loops

Self-loops affect neither the number of spanning trees nor the calculation of the Laplace matrix below, so the matrix-tree theorem remains valid in the presence of self-loops. There is no need to delete self-loops during computation. If self-loops are deleted, it affects the use of the matrix-tree theorem under the BEST theorem to count the number of Eulerian circuits in a directed graph.

Undirected graphs

Let GG be an undirected graph with nn vertices. Define its degree matrix D(G)D(G) by

Dii(G)=deg(i), Dij=0, i≠j.D_{ii}(G) = \mathrm{deg}(i),\ D_{ij} = 0,\ i\neq j.

Let #e(i,j)\#e(i,j) be the number of edges connecting vertices ii and jj, and define the adjacency matrix AA by

Aij(G)=Aji(G)=#e(i,j), i≠j.A_{ij}(G)=A_{ji}(G)=\#e(i,j),\ i\neq j.

Define the Laplace matrix (also called the Kirchhoff matrix) LL by

L(G)=D(G)−A(G).L(G) = D(G) - A(G).

Let the number of all spanning trees of GG be t(G)t(G).

Directed graphs

Let GG be a directed graph with nn vertices. Define its out-degree matrix Dout(G)D^{out}(G) by

Diiout(G)=degout(i), Dijout=0, i≠j.D^\mathrm{out}_{ii}(G) = \mathrm{deg}^\mathrm{out}(i),\ D^\mathrm{out}_{ij} = 0,\ i\neq j.

Define the in-degree matrix Din(G)D^\mathrm{in}(G) similarly.

Let #e(i,j)\#e(i,j) be the number of directed edges from vertex ii to vertex jj, and define the adjacency matrix AA by

Aij(G)=#e(i,j), i≠j.A_{ij}(G)=\#e(i,j),\ i\neq j.

Define the out-degree Laplace matrix LoutL^\mathrm{out} by

Lout(G)=Dout(G)−A(G).L^\mathrm{out}(G) = D^\mathrm{out}(G) - A(G).

Define the in-degree Laplace matrix LinL^\mathrm{in} by

Lin(G)=Din(G)−A(G).L^\mathrm{in}(G) = D^\mathrm{in}(G) - A(G).

Let the number of all arborescences of GG rooted at kk be troot(G,k)t^\mathrm{root}(G,k). An arborescence is a graph whose underlying graph is a tree and whose edges all point toward the root.

Let the number of all anti-arborescences of GG rooted at kk be tleaf(G,k)t^\mathrm{leaf}(G,k). An anti-arborescence is a graph whose underlying graph is a tree and whose edges all point away from the root.

Theorem statements

The matrix-tree theorem has several forms.

Define [n]={1,2,⋯ ,n}[n]=\{1,2,\cdots,n\}, and for a matrix AA, let its submatrix AS,TA_{S,T} be the matrix formed by selecting the elements Ai,j(i∈S,j∈T)A_{i,j}\pod{i\in S,j\in T}.

Theorem 1 (matrix-tree theorem, undirected graphs, determinant form)

For an undirected graph GG and any kk,

t(G)=det⁡L(G)[n]∖{k},[n]∖{k}.t(G) = \det L(G)_{[n]\setminus\{k\},[n]\setminus\{k\}}.

In other words, all principal minors of order n−1n-1 of the Laplace matrix of an undirected graph are equal, and all equal the number of spanning trees of the graph.

Corollary 1 (matrix-tree theorem, undirected graphs, eigenvalue form)

Let λ1≥λ2≥⋯≥λn−1≥λn=0\lambda_1\ge\lambda_2\ge\cdots\ge\lambda_{n-1}\ge\lambda_n=0 be the eigenvalues of L(G)L(G), of which there are nn. Then

t(G)=1nλ1λ2⋯λn−1.t(G) = \frac{1}{n}\lambda_1\lambda_2\cdots\lambda_{n-1}.
Theorem 2 (matrix-tree theorem, directed graphs, arborescences, determinant form)

For a directed graph GG and any kk,

troot(G,k)=det⁡Lout(G)[n]∖{k},[n]∖{k}.t^\mathrm{root}(G,k) = \det L^\mathrm{out}(G)_{[n]\setminus\{k\},[n]\setminus\{k\}}.

In other words, the principal minor obtained by deleting row kk and column kk from the out-degree Laplace matrix of a directed graph equals the number of arborescences rooted at kk.

Therefore, to count all arborescences of a graph, it suffices to enumerate every root kk and sum troot(G,k)t^\mathrm{root}(G,k).

Theorem 3 (matrix-tree theorem, directed graphs, anti-arborescences, determinant form)

For a directed graph GG and any kk,

tleaf(G,k)=det⁡Lin(G)[n]∖{k},[n]∖{k}.t^\mathrm{leaf}(G,k) = \det L^\mathrm{in}(G)_{[n]\setminus\{k\},[n]\setminus\{k\}}.

In other words, the principal minor obtained by deleting row kk and column kk from the in-degree Laplace matrix of a directed graph equals the number of anti-arborescences rooted at kk.

Therefore, to count all anti-arborescences of a graph, it suffices to enumerate every root kk and sum tleaf(G,k)t^\mathrm{leaf}(G,k).

Note

An arborescence is also called an in-tree, but because the out-degree is used when computing in-trees, the term arborescence is used here to avoid confusion between in\mathrm{in} and out\mathrm{out}.

Proof of the theorems

The forms of the theorems above are extremely similar. Here we give a unified proof and extend the previous conclusions to weighted graphs.

The proof proceeds roughly as follows:

  • First, every case can be reduced to counting arborescences in a directed graph;
  • use matrix language to give necessary and sufficient conditions for the selected edges to form an arborescence;
  • connect the edge-selection operation with the determinant of the Laplace matrix using the Cauchy–Binet formula;
  • finally, convert the determinant-form conclusion into the eigenvalue-form conclusion.

Lemma: the Cauchy–Binet formula

Lemma 1 (Cauchy–Binet)

Given an n×mn\times m matrix AA and an m×nm\times n matrix BB,

det⁡(AB)=∑S⊂[m]; ∣S∣=ndet⁡A[n],Sdet⁡BS,[n],\det(AB)=\sum_{S\subset[m];~|S|=n}\det A_{[n],S}\det B_{S,[n]},

where the summation means that SS ranges over all subsets of [m][m] of size nn. If n>mn>m, then necessarily det⁡(AB)=0\det(AB)=0.

Proof (combinatorial viewpoint)

Following the model from 「NOI2021」Path Intersections, first consider the following combinatorial interpretation of a determinant. For an n×nn\times n matrix CC, construct a directed acyclic graph G=(V,E)G=(V,E). Its vertex set is V=[2]×[n]⊂R2V=[2]\times[n]\subset\mathbb R^2, namely two columns of points in the plane. Denote the points in the left column by L={li=(1,i):i∈[n]}L=\{l_i=(1,i):i\in[n]\} and those in the right column by R={ri=(2,i):i∈[n]}R=\{r_i=(2,i):i\in[n]\}; the directed edge set is E={(li,rj):i,j∈[n]}E=\{(l_i,r_j):i,j\in[n]\}, and assign edge weight w(li,rj)=Ci,jw(l_i,r_j)=C_{i,j}. In this graph, call a subset of nn edges, Eσ⊂EE^\sigma\subset E, a path family if its starting points are pairwise distinct and its ending points are also pairwise distinct. Clearly, path families EσE^\sigma and permutations of [n][n], denoted σ\sigma, are in one-to-one correspondence. Notice that when a path family is drawn in the plane, its edges may intersect pairwise, and the number of intersection points, counted with multiplicity, equals the inversion number of σ\sigma. This is because edges (li,rσ(i))(l_i,r_{\sigma(i)}) and (lj,rσ(j))(l_j,r_{\sigma(j)}) intersect if and only if (i−j)(σ(i)−σ(j))<0(i-j)(\sigma(i)-\sigma(j))< 0, which is precisely an inversion pair. For convenience, call the parity of the inversion number of the corresponding permutation, equivalently the parity of the number of intersections in the path family, the parity of the path family. Thus, if these path families are counted by weight, the number of path families with an even number of intersections minus the number with an odd number of intersections gives the Leibniz expansion of the determinant:

det⁡(C)=∑σ∈Snsgn(σ)∏i∈[n]Ci,σ(i),\det(C)=\sum_{\sigma\in S_n}\mathrm{sgn}(\sigma)\prod_{i\in[n]}C_{i,\sigma(i)},

where SnS_n is the permutation group on [n][n], and sgn(σ)\mathrm{sgn}(\sigma) is the sign of permutation σ\sigma (it equals 11 when the inversion number is even and −1-1 when the inversion number is odd).

Once the combinatorial meaning of the determinant is understood, the Cauchy–Binet formula can be proved using the following combinatorial model. For an n×mn\times m matrix AA and an m×nm\times n matrix BB, construct a directed acyclic graph G=(V,E)G=(V,E). Its vertex set is V=L∪D∪RV=L\cup D\cup R, where L={li=(1,i):i∈[n]}L=\{l_i=(1,i):i\in[n]\}, D={di=(2,i):i∈[m]}D=\{d_i=(2,i):i\in[m]\}, and R={ri=(3,i):i∈[n]}R=\{r_i=(3,i):i\in[n]\}; its directed edge set is E=EL∪ERE=E_L\cup E_R, where EL={(li,dj):i∈[n],j∈[m]}E_L=\{(l_i,d_j):i\in[n],j\in[m]\} and ER={(dj,ri):j∈[m],i∈[n]}E_R=\{(d_j,r_i):j\in[m],i\in[n]\}, with edge weights w(li,dj)=Ai,jw(l_i,d_j)=A_{i,j} and w(dj,ri)=Bj,iw(d_j,r_i)=B_{j,i}, respectively. Again consider path families from LL through DD to RR, with paths pairwise sharing no vertices; count them by weight and subtract the count of path families with an odd number of intersections from the count with an even number of intersections. We now show that the two sides of the Cauchy–Binet formula compute this number in two ways.

For the left-hand side, based on the graph GG described above, construct a new graph G′G' whose vertex set is V′=L∪RV'=L\cup R and whose edge set is E′={(li,rj):i,j∈[n]}E'=\{(l_i,r_j):i,j\in[n]\}. Assign edge (li,rj)(l_i,r_j) the weight ∑k∈[m]Ai,kBk,j\sum_{k\in[m]}A_{i,k}B_{k,j}, namely, in the original graph GG, the weighted count of simple paths from lil_i to rjr_j. This edge weight is exactly (AB)i,j(AB)_{i,j}. This amounts to simplifying the three-layer graph into a two-layer graph. However, path families in the two-layer graph G′G' do not correspond one-to-one with path families in the three-layer graph GG. Since each path in the two-layer graph corresponds to several simple paths in the three-layer graph, counting path families in the two-layer graph requires multiplying their weights, which amounts to pairing the corresponding path sets in the three-layer graph. This inevitably produces cases in which paths share an intermediate stop. However, pairs of paths sharing an intermediate stop do not contribute to the final answer: for i1<i2i_1< i_2, j1<j2j_1< j_2, and any intermediate point dd, there are two pairs of simple paths, (li1→d→rj1,li2→d→rj2)(l_{i_1}\rightarrow d\rightarrow r_{j_1}, l_{i_2}\rightarrow d\rightarrow r_{j_2}) and (li1→d→rj2,li2→d→rj1)(l_{i_1}\rightarrow d\rightarrow r_{j_2}, l_{i_2}\rightarrow d\rightarrow r_{j_1}), but the parities of their numbers of intersections in the three-layer graph are necessarily opposite, because if only the starting and ending points are considered, the two path pairs exchange their endpoints. Therefore, these paths sharing an intermediate stop cancel in pairs when path families are counted in the simplified two-layer graph. For the remaining cases, once the starting and ending points of two paths are fixed, the parity of the number of their intersections does not change regardless of how the intermediate points are selected, as long as the same point is not selected twice. Thus, for each path family in G′G', all corresponding path families in the original graph GG have the same parity. Consequently, det⁡(AB)\det(AB) provides one way to compute the difference in the number of path families described above.

For the right-hand side, it enumerates all possible combinations of intermediate points. Given any intermediate-point set S⊂D=[m]S\subset D=[m] with ∣S∣=n|S|=n, consider path families from LL to SS and from SS to RR, respectively. They can be joined to obtain a path family from LL to RR, and the composition of the permutations corresponding to the first two path families is exactly the permutation corresponding to the resulting path family, so the product of the parities of the first two path families equals the parity of the resulting path family. Therefore, the difference in the counts of all path families whose intermediate-point set is SS is exactly the product of the difference in the counts of path families from LL to SS and from SS to RR. Summing over all possible SS gives the right-hand side, so it is precisely the difference in the number of path families described above.

Proof (algebraic viewpoint)

The combinatorial proof above can in fact be translated into an algebraic proof word for word. Here we instead give a more technically involved algebraic proof, using several common results. When m<nm< n, the determinant is zero because

rank(AB)≤min⁡{rank(A),rank(B)}≤m<n.\mathrm{rank}(AB)\le \min\{\mathrm{rank}(A),\mathrm{rank}(B)\}\le m< n.

When m=nm=n, the Cauchy–Binet formula is simply the fact that the determinant of a product of square matrices equals the product of their determinants.

When m>nm>n, note that

xm−ndet⁡(xIn+AB)=det⁡(xIm+BA).x^{m-n}\det(xI_n+AB) = \det(xI_m+BA).

It is also known that, for det⁡(xIn+C)\det(xI_n+C), the coefficient of xn−kx^{n-k} is the sum of all principal minors of CC of order kk. Therefore, comparing coefficients on both sides of the equation above gives

det⁡(AB)=∑S⊂[m]; ∣S∣=ndet⁡(BA)S,S=∑S⊂[m]; ∣S∣=ndet⁡(B)S,[n]det⁡(A)[n],S=∑S⊂[m]; ∣S∣=ndet⁡(A)[n],Sdet⁡(B)S,[n].\det(AB) = \sum_{S\subset[m];~|S|=n}\det(BA)_{S,S} = \sum_{S\subset[m];~|S|=n}\det(B)_{S,[n]}\det(A)_{[n],S} = \sum_{S\subset[m];~|S|=n}\det(A)_{[n],S}\det(B)_{S,[n]}.

Here, the second equality uses the result for the case m=nm=n.

Characterizing graph structure with incidence matrices

For a directed graph G=(V,E)G=(V,E) with nn vertices and mm edges, assign each edge ee an edge weight w(e)w(e). We can then define the m×nm\times n out-incidence matrix

Mijout={w(ei),∃u(ei=(vj,u)),0,otherwise,M^\mathrm{out}_{ij}=\begin{cases} \sqrt{w(e_i)},&\exists u(e_i=(v_j,u)),\\ 0,&\textrm{otherwise}, \end{cases}

and the m×nm\times n in-incidence matrix

Mijin={w(ei),∃u(ei=(u,vj)),0,otherwise.M^\mathrm{in}_{ij}=\begin{cases} \sqrt{w(e_i)},&\exists u(e_i=(u,v_j)),\\ 0,&\textrm{otherwise}. \end{cases}

Each row records one edge: the out-incidence matrix MoutM^\mathrm{out} records the starting point of the edge, while the in-incidence matrix MinM^\mathrm{in} records its ending point.

A direct calculation gives

Dout(G)=(Mout)TMout, A(G)=(Mout)TMin, Din(G)=(Min)TMin.D^\mathrm{out}(G) = (M^\mathrm{out})^T M^\mathrm{out},\ A(G) = (M^\mathrm{out})^T M^\mathrm{in},\ D^\mathrm{in}(G) = (M^\mathrm{in})^T M^\mathrm{in}.

Consequently,

Lout(G)=(Mout)T(Mout−Min), Lin(G)=(Min−Mout)TMin.L^\mathrm{out}(G) = (M^\mathrm{out})^T (M^\mathrm{out}-M^\mathrm{in}),\ L^\mathrm{in}(G) = (M^\mathrm{in}-M^\mathrm{out})^T M^\mathrm{in}.

The Cauchy–Binet formula above shows that a principal minor of the Laplace matrix is actually a sum over a series of substructures. Each substructure reflects a property of the corresponding subgraph.

Lemma 2

For GG and one of its subgraphs (W,S)(W,S), if it satisfies ∣W∣=∣S∣≤n|W|=|S|\le n, then the subgraph T=(V,S)T=(V,S) is a rooted forest with V∖WV\setminus W as its roots if and only if

det⁡(MS,Wout)det⁡(MS,Wout−MS,Win)\det(M^\mathrm{out}_{S,W})\det(M^\mathrm{out}_{S,W}-M^\mathrm{in}_{S,W})

is nonzero. Moreover, when this expression is nonzero, it necessarily equals ∏e∈Sw(e)\prod_{e\in S}w(e); denote it by w(T)w(T).

Proof

Without loss of generality, assume w(e)=1w(e)=1. By the multilinearity of determinants, each determinant can have w(e)\sqrt{w(e)} factored out of every row, and the product of these factors is w(T)w(T).

First analyze the conditions under which the two factors are zero. Each row of the first factor det⁡(MS,Wout)\det(M^\mathrm{out}_{S,W}) has at most one nonzero entry, namely +1+1. If any row is all zero, the determinant must be zero. Thus, the determinant is nonzero if and only if every row has exactly one +1+1; that is, every vertex in WW is the starting point of exactly one edge in SS, and no two edges share the same starting point. If TT is a rooted forest with V∖WV\setminus W as its roots, a necessary condition is that every non-root vertex has exactly one outgoing edge, which necessarily makes this factor nonzero; but the converse does not always hold, because it does not guarantee the absence of cycles, so the second factor must also be examined. Note that the endpoints of edges in SS need not lie in WW.

Assume that the first factor is nonzero. Then the subgraph TT is a rooted forest if and only if TT contains no cycle. In this case, every row of the latter expression det⁡(MS,Wout−MS,Win)\det(M^\mathrm{out}_{S,W}-M^\mathrm{in}_{S,W}) has one +1+1, but may have either one or zero −1-1 entries. For an edge whose endpoint is also in WW, if the endpoint of eie_i is the starting point of eje_j, add to the row for eie_i the row for eje_j; this eliminates, in row eie_i, the −1-1. One may imagine that this row now describes the simple path formed by joining eie_i and eje_j end to end. If a new −1-1 appears in the row, then the endpoint of eje_j is also in WW, and the position of −1-1 is the endpoint of eje_j. We can therefore continue by finding the edge starting at the endpoint of eje_j and adding its row to the current row. Such an edge always exists, because the preceding argument shows that every point in WW is the starting point of exactly one edge in SS. This process continues until the row no longer contains a −1-1, which is equivalent to continuously adding new edges to the simple path ei→ej→⋯→eke_i\rightarrow e_j\rightarrow \cdots\rightarrow e_k. If the row then contains only one +1+1, the endpoint of eke_k is not in the selected vertex set WW, so the process terminates; if the last added edge happens to cancel the existing +1+1, leaving the row all zero, then the endpoint of the new edge eke_k is the starting point of the initial edge eie_i, so a cycle has appeared. Thus, the necessary and sufficient condition for the absence of cycles is that this determinant can, after the operations above, be transformed into a form in which every row has exactly one +1+1. Since these +1+1 entries are at the starting points of the corresponding edges, the resulting matrix is exactly det⁡(MS,Wout)\det(M^\mathrm{out}_{S,W}).

In summary, if TT is not a rooted forest, then either det⁡(MS,Wout)=0\det(M^\mathrm{out}_{S,W})=0 or det⁡(MS,Wout−MS,Win)=0\det(M^\mathrm{out}_{S,W}-M^\mathrm{in}_{S,W})=0; otherwise, both are nonzero and their product is (det⁡(MS,Wout))2=1\left(\det(M^\mathrm{out}_{S,W})\right)^2=1.

The matrix-tree theorem for weighted directed graphs

We can now prove the main result of this article. All the matrix-tree theorems stated earlier are special cases of this theorem.

Theorem 4 (matrix-tree theorem, weighted directed graphs, arborescences, determinant form)

For any kk,

∑T∈Troot(G,k)w(T)=det⁡Lout(G)[n]∖{k},[n]∖{k}.\sum_{T\in\mathcal T^\mathrm{root}(G,k)}w(T)=\det L^\mathrm{out}(G)_{[n]\setminus\{k\},[n]\setminus\{k\}}.

Here, Troot(G,k)\mathcal T^\mathrm{root}(G,k) is the set of arborescences of GG rooted at kk.

Proof

Let W=[n]∖{k}W=[n]\setminus\{k\} be the set of vertices other than kk. Then, by the Cauchy–Binet formula, the right-hand side can be written as

det⁡Lout(G)W,W=∑S⊂[m]; ∣S∣=n−1det⁡(MS,Wout)det⁡(MS,Wout−MS,Win).\det L^\mathrm{out}(G)_{W,W} = \sum_{S\subset[m];~|S|=n-1}\det(M^\mathrm{out}_{S,W})\det(M^\mathrm{out}_{S,W}-M^\mathrm{in}_{S,W}).

As SS ranges over all possibilities, by Lemma 2, if and only if T=(V,S)T=(V,S) forms a rooted forest with V∖W={k}V\setminus W=\{k\} as its root set, that is, if and only if TT is an arborescence rooted at kk, the right-hand side accumulates w(T)w(T).

When w(e)=1w(e)=1, every tree has weight 11, so the left-hand side is exactly the count of all trees, namely troot(G,k)t^\mathrm{root}(G,k), which gives Theorem 2. As above, the conclusion can be directly extended to anti-arborescences, giving Theorem 3. Finally, to count spanning trees in an undirected graph, we can apply the following corollary.

Corollary 4 (matrix-tree theorem, weighted undirected graphs, determinant form)

For an undirected graph GG and any kk,

∑T∈T(G)w(T)=det⁡L(G)[n]∖{k},[n]∖{k}.\sum_{T\in\mathcal T(G)}w(T) = \det L(G)_{[n]\setminus\{k\},[n]\setminus\{k\}}.

Here, T(G)\mathcal T(G) is the set of spanning trees of GG. This also shows that all principal minors of L(G)L(G) of order (n−1)(n-1) are equal.

Proof

For an undirected graph G=(V,E)G=(V,E), construct a directed graph G′=(V,E′)G'=(V,E'), where E′={(vi,vj):(vi,vj)∈E}∪{(vj,vi):(vi,vj)∈E}E'=\{(v_i,v_j):(v_i,v_j)\in E\}\cup\{(v_j,v_i):(v_i,v_j)\in E\}; that is, every undirected edge in GG is split into two oppositely directed edges in the directed graph. Fix any kk. Then the arborescences in G′G' rooted at kk and the spanning trees in GG are in one-to-one correspondence. From the former to the latter, we only need to remove the orientations of the edges and the choice of root; from the latter to the former, we only need to start from the selected root kk and orient each edge toward the root. Therefore,

∑T∈T(G)w(T)=∑T∈Troot(G′,k)w(T)=det⁡Lout(G′)[n]∖{k},[n]∖{k}=det⁡L(G)[n]∖{k},[n]∖{k}.\sum_{T\in\mathcal T(G)}w(T) = \sum_{T\in\mathcal T^\mathrm{root}(G',k)}w(T) = \det L^\mathrm{out}(G')_{[n]\setminus\{k\},[n]\setminus\{k\}} = \det L(G)_{[n]\setminus\{k\},[n]\setminus\{k\}}.

Here we use Lout(G′)=L(G)L^\mathrm{out}(G')=L(G), which is straightforward to verify directly.

Eigenvalue form

We still begin with the result for directed graphs.

Theorem 5

For a directed graph GG, define the multivariate polynomial

χ(x1,⋯ ,xn)=det⁡(diag(x1,⋯ ,xn)−Lout(G)).\chi(x_1,\cdots,x_n)=\det(\mathrm{diag}(x_1,\cdots,x_n)-L^\mathrm{out}(G)).

Here, diag(x1,⋯ ,xn)\mathrm{diag}(x_1,\cdots,x_n) denotes the diagonal matrix whose diagonal entries are x1,⋯ ,xnx_1,\cdots,x_n. Then,

(−1)n−r[xk1,⋯ ,xkr]χ(x1,⋯ ,xn)(-1)^{n-r}[x_{k_1},\cdots,x_{k_r}]\chi(x_1,\cdots,x_n)

equals the weighted count of rooted forests of GG whose root set is {k1,⋯ ,kr}\{k_1,\cdots,k_r\}.

Proof

Following the proof of Theorem 4, let W=[n]∖{k1,⋯ ,kr}W=[n]\setminus\{k_1,\cdots,k_r\}. Then the coefficient in the theorem is det⁡Lout(G)W,W\det L^\mathrm{out}(G)_{W,W} (this can be seen directly from the Leibniz expansion of the determinant). By the Cauchy–Binet formula, it equals

det⁡Lout(G)W,W=∑S⊂[m]; ∣S∣=n−rdet⁡(MS,Wout)det⁡(MS,Wout−MS,Win).\det L^\mathrm{out}(G)_{W,W} = \sum_{S\subset[m];~|S|=n-r}\det(M^\mathrm{out}_{S,W})\det(M^\mathrm{out}_{S,W}-M^\mathrm{in}_{S,W}).

As SS ranges over all possibilities, by Lemma 2, the condition that T=(V,S)T=(V,S) forms a rooted forest with V∖W={k1,⋯ ,kr}V\setminus W=\{k_1,\cdots,k_r\} as its root set is exactly the condition for the right-hand side to accumulate w(T)w(T).

Substitute xx for every indeterminate to obtain the characteristic polynomial of the Laplace matrix

P(x)=det⁡(xI−Lout(G))=χ(x,⋯ ,x).P(x) = \det(xI-L^\mathrm{out}(G)) = \chi(x,\cdots,x).
Lemma 3

The Laplace matrix Lout(G)L^\mathrm{out}(G) has at least one eigenvalue equal to zero.

Proof

It suffices to prove that its determinant is zero. Following the proofs of Theorems 4 and 5, take W=∅W=\varnothing. Then this determinant should equal the number of rooted forests with zero trees. Such a forest does not exist, so the determinant is zero.

Corollary 5

For a directed graph GG, the sum of the weights of all rooted forests consisting of kk trees equals the coefficient

(−1)n−k[xk]P(x).(-1)^{n-k}[x^k]P(x).
Proof

Sum over all possible choices of the kk roots.

Define a kk-spanning forest as a spanning subgraph of a graph with kk connected components and no cycles.

Corollary 6

For an undirected graph GG, let the set of its kk-spanning forests be Tk(G)\mathcal T_k(G). Then

∑T∈Tk(G)w(T)Q(T)=(−1)n−k[xk]P(x).\sum_{T\in\mathcal T_k(G)}w(T)Q(T) = (-1)^{n-k}[x^k]P(x).

Here, Q(T)Q(T) is the product of the numbers of vertices in each connected component of the forest TT. In particular, when k=1k=1, we have Q(T)=nQ(T)=n, and hence

n∑T∈T(G)w(T)=λ1λ2⋯λn−1.n\sum_{T\in\mathcal T(G)}w(T) = \lambda_1\lambda_2\cdots\lambda_{n-1}.
Proof

As in the proof of Corollary 4, we can directly use the conclusion of Corollary 5. Every rooted forest consisting of kk trees in the directed graph corresponds to a kk-spanning forest in the undirected graph. However, each kk-spanning forest TT has Q(T)Q(T) choices of roots, so it appears in Q(T)Q(T) rooted forests of the directed graph.

Applications

Cayley's formula

Corollary 7 (Cayley)

There are nn-vertex labeled unrooted trees, of which there are nn−2n^{n-2}.

Proof

Equivalently, it suffices to show that the number of spanning trees of the complete graph on nn vertices is nn−2n^{n-2}. To this end, write its Laplace matrix as

L(G)=(n−1−1⋯−1−1n−1⋯−1⋮⋮⋱⋮−1−1⋯n−1)n×n.L(G) = \left(\begin{matrix} n-1 & -1 & \cdots & -1 \\ -1 & n-1 & \cdots & -1 \\ \vdots & \vdots & \ddots & \vdots \\ -1 & -1 & \cdots & n-1 \end{matrix}\right)_{n\times n}.

Computing any principal minor gives

det⁡(nIn−1−11T)=nn−1det⁡(In−1−n−111T)=nn−1(1−n−11T1)=nn−1(1−(n−1)/n)=nn−2.\det(nI_{n-1}-{\bf 1}{\bf 1}^T) = n^{n-1}\det(I_{n-1}-n^{-1}{\bf 1}{\bf 1}^T) = n^{n-1}(1-n^{-1}{\bf 1}^T{\bf 1}) = n^{n-1}(1-(n-1)/n) = n^{n-2}.

The result follows from Theorem 1.

The BEST theorem

Prerequisite: Eulerian graph

This theorem relates the number of Eulerian circuits in a directed Eulerian graph to the number of arborescences of the graph, thereby solving the problem of counting Eulerian circuits in directed graphs. Note that counting Eulerian circuits in an arbitrary undirected graph is NP-complete.

When implementing this algorithm, first determine whether the given graph is Eulerian, remove all zero-degree vertices, then build the graph and calculate the number of arborescences, and use the BEST theorem to obtain the number of Eulerian circuits. Note that if the requested number of Eulerian circuits requires starting from a given vertex, the answer must be multiplied by the out-degree of that vertex, which is equivalent to enumerating the first edge of the circuit.

Before proving the BEST theorem, we need the following result.

Property (testing whether a directed graph has an Eulerian circuit)

A directed graph has an Eulerian circuit if and only if its nonzero-degree vertices are strongly connected and the out-degree equals the in-degree at every vertex.

For an Eulerian graph, since the out-degree and in-degree are equal, we omit the superscript and write deg(v)\mathrm{deg}(v). The BEST theorem can be stated as follows.

Theorem 6 (BEST theorem)

Let GG be a directed Eulerian graph, and let kk be any vertex. Then the total number of distinct Eulerian circuits of GG, ec(G)\mathrm{ec}(G), is

ec(G)=troot(G,k)∏v∈V(deg⁡(v)−1)!.\mathrm{ec}(G) = t^\mathrm{root}(G,k)\prod_{v\in V}(\deg (v) - 1)!.

This also shows that for any Eulerian graph GG and any two vertices k,k′k, k', we have troot(G,k)=troot(G,k′)t^\mathrm{root}(G,k)=t^\mathrm{root}(G,k').

Proof

The basic idea of the proof is to establish a correspondence between Eulerian circuits starting at kk, arborescences rooted at kk, and permutations of the outgoing edges at each vertex. After fixing the starting vertex of the Eulerian circuit, the count to be proved should be

deg(k)ec(G)=troot(G,k)deg⁡(k)!∏v≠k(deg⁡(v)−1)!.\mathrm{deg}(k)\mathrm{ec}(G) = t^\mathrm{root}(G,k)\deg(k)!\prod_{v\neq k}(\deg (v) - 1)!.

The combinatorial meaning of this count leads to the following construction. For an Eulerian circuit starting at kk, according to the order in which each edge appears in the circuit, construct

  • an arborescence rooted at kk, consisting of the last outgoing edge at every non-root vertex, giving troot(G,k)t^\mathrm{root}(G,k);
  • the ordering of all outgoing edges at the root kk, giving deg(k)!\mathrm{deg}(k)!; and
  • at each non-root vertex v≠kv\neq k, the ordering of all outgoing edges other than the last one, giving (deg(v)−1)!(\mathrm{deg}(v)-1)!.

We now show that this construction gives a bijection.

In one direction, given an Eulerian circuit, we must prove that the last outgoing edges at all non-root vertices form an arborescence. By construction, every non-root vertex in the tree has exactly one outgoing edge, so it remains only to prove that these outgoing edges do not form a cycle. If all vertices are ordered according to the order of their last appearances in the Eulerian circuit, then the last outgoing edge of every non-root vertex must point to a vertex that appears strictly later in this order. If a cycle existed, it would contain a vertex that appears latest in the order; because this vertex lies on the cycle, it would point to a vertex that does not appear later, contradicting the statement above. Thus, the last outgoing edges of all non-root vertices necessarily form an arborescence.

In the other direction, given any arborescence and an ordering of all the other outgoing edges, we can reconstruct an Eulerian circuit such that applying the construction above to it yields the given arborescence and ordering. Starting from the root kk, whenever a vertex is reached, choose as the next edge of the Eulerian circuit the earliest unused outgoing edge according to the given ordering at that vertex; if all outgoing edges in the ordering at that vertex have been used, choose the outgoing edge of that vertex in the arborescence as the next edge of the Eulerian circuit. Since the graph is Eulerian, every vertex has equal in-degree and out-degree, so this process cannot terminate at a non-root vertex; the resulting path is therefore a circuit. To prove that the resulting path is a valid Eulerian circuit, it suffices to show that this process traverses every edge.

If it does not, there must be some vertex vv with an outgoing edge that has not been traversed. Consider vertex vv. Vertex vv cannot be the root, because the process eventually terminates at the root, and if the root still had an unused outgoing edge, that would contradict the termination of the process. Thus, vv is not the root. By the process described above, as long as a non-root vertex vv has any outgoing edge remaining, its outgoing edge ee in the arborescence must also remain. Let e=(v,u)e=(v,u). Since some incoming edge of uu has not been traversed, and the out-degree of uu equals its in-degree, some outgoing edge of uu must not have been traversed either. We can then examine vertex uu in the same way. This reasoning moves the vertex under consideration from vv to uu, namely one step toward the root along the arborescence. By induction, there must then be an unused outgoing edge of the root kk. The preceding argument has already shown that this is impossible, giving a contradiction. Therefore, the path obtained in the preceding paragraph is indeed a valid Eulerian circuit.

It can be verified that these maps are injective, and hence they are bijections. The proposition follows.

Implementation

Write the Laplace matrix from the graph, delete one row and one column, and compute the determinant of the resulting matrix. The determinant can be computed using Gaussian elimination.

For example, the number of spanning trees of a square graph is

(2000020000200002)−(0101101001011010)=(2−10−1−12−100−12−1−10−12)\begin{pmatrix} 2 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \\ 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 2 \end{pmatrix}-\begin{pmatrix} 0 & 1 & 0 & 1 \\ 1 & 0 & 1 & 0 \\ 0 & 1 & 0 & 1 \\ 1 & 0 & 1 & 0 \end{pmatrix}=\begin{pmatrix} 2 & -1 & 0 & -1 \\ -1 & 2 & -1 & 0 \\ 0 & -1 & 2 & -1 \\ -1 & 0 & -1 & 2 \end{pmatrix} ∣2−10−12−10−12∣=4\begin{vmatrix} 2 & -1 & 0 \\ -1 & 2 & -1 \\ 0 & -1 & 2 \end{vmatrix} = 4

This can be solved with Gaussian elimination, with time complexity O(n3)O(n^3).

Implementation
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
constexpr int MOD = 100000007;
constexpr double eps = 1e-7;

struct matrix {
  static constexpr int MAXN = 20;
  int n, m;
  double mat[MAXN][MAXN];

  matrix() { memset(mat, 0, sizeof(mat)); }

  void print() {
    cout << "MATRIX " << n << " " << m << endl;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << mat[i][j] << "\t";
      }
      cout << endl;
    }
  }

  void random(int n) {
    this->n = n;
    this->m = n;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++) mat[i][j] = rand() % 100;
  }

  void initSquare() {
    this->n = 4;
    this->m = 4;
    memset(mat, 0, sizeof(mat));
    mat[0][1] = mat[0][3] = 1;
    mat[1][0] = mat[1][2] = 1;
    mat[2][1] = mat[2][3] = 1;
    mat[3][0] = mat[3][2] = 1;
    mat[0][0] = mat[1][1] = mat[2][2] = mat[3][3] = -2;
    this->n--;  // remove one row
    this->m--;  // remove one column
  }

  double gauss() {
    double ans = 1;
    for (int i = 0; i < n; i++) {
      int sid = -1;
      for (int j = i; j < n; j++)
        if (abs(mat[j][i]) > eps) {
          sid = j;
          break;
        }
      if (sid == -1) continue;
      if (sid != i) {
        for (int j = 0; j < n; j++) {
          swap(mat[sid][j], mat[i][j]);
          ans = -ans;
        }
      }
      for (int j = i + 1; j < n; j++) {
        double ratio = mat[j][i] / mat[i][i];
        for (int k = 0; k < n; k++) {
          mat[j][k] -= mat[i][k] * ratio;
        }
      }
    }
    for (int i = 0; i < n; i++) ans *= mat[i][i];
    return abs(ans);
  }
};

int main() {
  srand(1);
  matrix T;
  // T.random(2);
  T.initSquare();
  T.print();
  double ans = T.gauss();
  T.print();
  cout << ans << endl;
}

Examples

Example 1: 「HEOI2015」Z's Room

Solution This is a basic application of the matrix-tree theorem. Treat each empty room as a node, build the graph according to the input, obtain the Laplace matrix, then delete from LL row ii and column ii, and compute the determinant of the resulting minor. The determinant is computed by using Gaussian elimination to reduce the matrix to upper triangular form and then taking the product of the diagonal entries. In addition, this problem requires Gaussian elimination over the integer subring modulo kk, Zk\mathbb{Z}_k; the Euclidean algorithm can be used.

Example 2: 「FJOI2007」Whirling Virus

Solution There are many solutions to this problem, and using the matrix-tree theorem is the most direct. When the input is nn, it is easy to write its Laplace matrix of order n+1n+1 as:

Ln=[n−1−1−1⋯−1−1−13−10⋯0−1−1−13−1⋯00−10−13⋯00⋮⋮⋮⋮⋱⋮⋮−1000⋯3−1−1−100⋯−13]n+1L_n = \begin{bmatrix} n& -1& -1& -1& \cdots& -1& -1\\ -1& 3& -1& 0& \cdots& 0& -1\\ -1& -1& 3& -1& \cdots& 0& 0\\ -1& 0& -1& 3& \cdots& 0& 0\\ \vdots& \vdots& \vdots& \vdots& \ddots& \vdots& \vdots\\ -1& 0& 0& 0& \cdots& 3& -1\\ -1& -1& 0& 0& \cdots& -1& 3\\ \end{bmatrix}_{n+1}

It suffices to compute the determinant of its order-nn minor; the only remaining issue is high-precision computation.

Example 2+

Strengthen the data of Example 2 by requiring n≤100000n\leq 100000, while the answer is taken modulo 1000007. (Solving this problem requires some linear algebra knowledge.)

Solution After deriving the recurrence, it can be computed using matrix exponentiation.

The derivation of the recurrence is as follows:

Notice that after deleting the first row and first column of LnL_n, the resulting matrix has a very regular form, so we are actually computing the determinant of

Mn=[3−10⋯0−1−13−1⋯000−13⋯00⋮⋮⋮⋱⋮⋮000⋯3−1−100⋯−13]nM_n = \begin{bmatrix} 3& -1& 0& \cdots& 0& -1\\ -1& 3& -1& \cdots& 0& 0\\ 0& -1& 3& \cdots& 0& 0\\ \vdots& \vdots& \vdots& \ddots& \vdots& \vdots\\ 0& 0& 0& \cdots& 3& -1\\ -1& 0& 0& \cdots& -1& 3\\ \end{bmatrix}_{n}

Expanding the determinant of MnM_n along its first column gives

det⁡Mn=3det⁡[3−1⋯00−13⋯00⋮⋮⋱⋮⋮00⋯3−100⋯−13]n−1+det⁡[−10⋯0−1−13⋯00⋮⋮⋱⋮⋮00⋯3−100⋯−13]n−1+(−1)ndet⁡[−10⋯0−13−1⋯00−13⋯00⋮⋮⋱⋮⋮00⋯3−1]n−1\det M_n = 3\det \begin{bmatrix} 3& -1& \cdots& 0& 0\\ -1& 3& \cdots& 0& 0\\ \vdots& \vdots& \ddots& \vdots& \vdots\\ 0& 0& \cdots& 3& -1\\ 0& 0& \cdots& -1& 3\\ \end{bmatrix}_{n-1} + \det\begin{bmatrix} -1& 0& \cdots& 0& -1\\ -1& 3& \cdots& 0& 0\\ \vdots& \vdots& \ddots& \vdots& \vdots\\ 0& 0& \cdots& 3& -1\\ 0& 0& \cdots& -1& 3\\ \end{bmatrix}_{n-1} + (-1)^n \det\begin{bmatrix} -1& 0& \cdots& 0& -1\\ 3& -1& \cdots& 0& 0\\ -1& 3& \cdots& 0& 0\\ \vdots& \vdots& \ddots& \vdots& \vdots\\ 0& 0& \cdots& 3& -1\\ \end{bmatrix}_{n-1}

Denote the determinants of the three matrices above by dn−1,an−1,bn−1d_{n-1}, a_{n-1}, b_{n-1}, respectively.
Notice that dnd_n is a tridiagonal determinant; by a similar expansion, we obtain that dnd_n satisfies the recurrence dn=3dn−1−dn−2d_n=3d_{n-1}-d_{n-2}. Similarly, expanding gives an−1=−dn−2−1a_{n-1}=-d_{n-2}-1 and (−1)nbn−1=−dn−2−1(-1)^n b_{n-1}=-d_{n-2}-1.
Substituting these recurrences into the expression above gives:

det⁡Mn=3dn−1−2dn−2−2\det M_n = 3d_{n-1}-2d_{n-2}-2 dn=3dn−1−dn−2d_n = 3d_{n-1}-d_{n-2}

We can therefore conjecture that det⁡Mn\det M_n also satisfies a nonhomogeneous second-order linear recurrence. Using the method of undetermined coefficients, the final recurrence is

det⁡Mn=3det⁡Mn−1−det⁡Mn−2+2\det M_n = 3\det M_{n-1} - \det M_{n-2} + 2

Rewriting it as (det⁡Mn+2)=3(det⁡Mn−1+2)−(det⁡Mn−2+2)(\det M_n+2) = 3(\det M_{n-1}+2) - (\det M_{n-2} + 2) and then using matrix exponentiation yields the answer.

Example 3: 「BZOJ3659」WHICH DREAMED IT

Solution This problem is a direct application of the BEST theorem. However, note that because the problem specifies that 「two ways of completing the task are considered different if and only if the order of using the keys is different」, for every Eulerian circuit, room 1 may start along any outgoing edge, so the answer must also be multiplied by the out-degree of room 1.

Example 4: 「United Provincial Selection 2020 A」The Assignment Problem

Solution First, Möbius inversion is needed to transform the problem into computing the sum of the edge weights of all spanning trees; this is omitted because it is not closely related to this article.

Write the terms of the determinant as wix+1w_ix+1. The final answer is the coefficient of the first-degree term of the determinant, because the answer is actually the number of spanning trees after designating one edge ×\times the sum of the weight of that edge, so the edge whose weight contributes to the first-degree coefficient is the designated edge. Terms of degree higher than one can be ignored, giving complexity O(n3)O(n^3).

「Beijing Provincial Selection Training 2019」Counting Spanning Trees is a more general case: to compute the sum of the kk-th powers of the sums of spanning-tree weights, construct the terms of the determinant in a similar way; see the Luogu solution for details.

Example 5: AGC051D C4

Solution Counting Eulerian circuits in an undirected graph is an NPC problem, but the graph in this problem is relatively simple. Once the number of edges among the S−TS-T edges directed from SS to TT is determined, the orientations of the other three types of edges are determined, and the BEST theorem directly gives a solution with complexity O(a+b+c+d)O(a+b+c+d).

This content comes from OI Wiki: Matrix-Tree Theorem. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.