home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 9 / 09.iso / e / e032 / 3.ddi / FILES / DISCRETE.PAK / COMBINAT.M < prev    next >
Encoding:
Text File  |  1992-07-29  |  102.2 KB  |  3,382 lines

  1. (* :Title: Combinatorica 
  2. *)
  3. (* :Author:
  4.     Steven S. Skiena 
  5. *)
  6. (* :Summary:
  7.  
  8.     Implementing Discrete Mathematics: Combinatorics and Graph Theory
  9.                 with Mathematica
  10.  
  11. This package contains all the programs from the book, "Implementing
  12. Discrete Mathematics: Combinatorics and Graph Theory with Mathematica"
  13. by Steven S. Skiena, Addison-Wesley Publishing Co., Advanced Book Program,
  14. 350 Bridge Parkway, Redwood City CA 94065.  ISBN 0-201-50943-1.
  15. For ordering information, call 1-800-447-2226.
  16.  
  17. These programs can be obtained on Macintosh and MS-DOS disks by sending
  18. $15.00 to Discrete Mathematics Disk, Wolfram Research Inc.,
  19. PO Box 6059, Champaign, IL 61826-9905. (217)-398-0700.
  20.  
  21. Any comments, bug reports, or requests to get on the Combinatorica
  22. mailing list should be forwarded to:
  23.  
  24.     Steven Skiena
  25.     Department of Computer Science
  26.     State University of New York
  27.     Stony Brook, NY 11794
  28.  
  29.     skiena@sbcs.sunysb.edu
  30.  
  31.     (516)-632-9026 / 8470
  32. *)
  33. (* :Context: DiscreteMath`Combinatorica` 
  34. *)
  35. (* :Package Version: .9    (2/29/92 Beta Release)
  36. *)
  37. (* :Copyright: Copyright 1990, 1991, 1992 by Steven S. Skiena
  38.  
  39. This package may be copied in its entirety for nonprofit purposes only.
  40. Sale, other than for the direct cost of the media, is prohibited.  This
  41. copyright notice must accompany all copies.
  42.  
  43. The author, Wolfram Research, and Addison-Wesley Publishing Company,
  44. Inc. make no representations, express or implied, with respond to this
  45. documentation, of the software it describes and contains, including
  46. without limitations, any implied warranties of mechantability or fitness
  47. for a particular purpose, all of which are expressly disclaimed.  The
  48. author, Wolfram Research, or Addison-Wesley, their licensees,
  49. distributors and dealers shall in no event be liable for any indirect,
  50. incidental, or consequential damages.
  51. *)
  52. (* :History:
  53.     Version .8 by Steven S. Skiena, July 1991.
  54.     Version .7 by Steven S. Skiena, January 1991. 
  55.     Version .6 by Steven S. Skiena, June 1990.
  56. *)
  57. (* :Keywords:
  58.     adjacency, automorphism, chromatic, clique, coloring,
  59.     combination, composition, connected components, connectivity, cycle,
  60.     de Bruijn, degree, derangement, Dijkstra, Durfee,
  61.     embedding, equivalence, Eulerian, Ferrers,
  62.     geodesic, graph, Gray code, group, Hamiltonian cycle, Harary, Hasse,
  63.     heap, hypercube, interval, inversion, involution, isomorphism,
  64.     Josephus, network,
  65.     partition, perfect, permutation, planar graph, Polya, pseudograph,
  66.     self-loop, sequence, signature, simple, spanning tree,
  67.     stable marriage, star, Stirling,
  68.     transitive closure, traveling salesman tour, tree, Turan,
  69.     vertex cover, wheel, Young tableau
  70. *)
  71. (* :Source:
  72.     Steven Skiena: "Implementing Discrete Mathematics: Combinatorics
  73.             and Graph Theory with Mathematica", 
  74.             Addison-Wesley Publishing Co.
  75. *)
  76. (* :Mathematica Version: 2.0
  77. *)
  78.  
  79. BeginPackage["DiscreteMath`Combinatorica`"]
  80.  
  81. Graph::usage = "Graph[g,v] is the header for a graph object where g is an adjacency matrix and v is a list of vertices."
  82.  
  83. Directed::usage = "Directed is an option to inform certain functions that the graph is directed."
  84.  
  85. Undirected::usage = "Undirected is an option to inform certain functions that the graph is undirected."
  86.  
  87. Edge::usage = "Edge is an option to inform certain functions to work with edges instead of vertices."
  88.  
  89. All::usage = "All is an option to inform certain functions to return all solutions, instead of just the first one."
  90.  
  91. AcyclicQ::usage = "AcyclicQ[g] returns True if graph g is acyclic. AcyclicQ[g,Directed] returns True if g is a directed acyclic graph."
  92.  
  93. AddEdge::usage = "AddEdge[g,{x,y}] returns graph g with a new undirected edge {x,y}, while AddEdge[g,{x,y},Directed] returns graph g with a new directed edge {x,y}."
  94.  
  95. AddVertex::usage = "AddVertex[g] adds a disconnected vertex to graph g."
  96.  
  97. AllPairsShortestPath::usage = "AllPairsShortestPath[g] returns a matrix, where the (i,j)th entry is the length of the shortest path in g between vertices i and j."
  98.  
  99. ArticulationVertices::usage = "ArticulationVertices[g] returns a list of all articulation vertices in graph g, vertices whose removal will disconnect the graph."
  100.  
  101. Automorphisms::usage = "Automorphisms[g] finds the automorphism group of a graph g, the set of isomorphisms of g with itself."
  102.  
  103. Backtrack::usage = "Backtrack[s,partialQ,solutionQ] performs a backtrack search of the state space s, expanding a partial solution so long as partialQ is True and returning the first complete solution, as identified by solutionQ."
  104.  
  105. BiconnectedComponents::usage = "BiconnectedComponents[g] returns a list of all the biconnected components of graph g."
  106.  
  107. BiconnectedComponents::usage = "BiconnectedComponents[g] returns a list of the biconnected components of graph g."
  108.  
  109. BiconnectedQ::usage = "BiconnectedQ[g] returns True if graph g is biconnected."
  110.  
  111. BinarySearch::usage = "BinarySearch[l,k,f] searches sorted list l for key k and returns the the position of l containing k, with f a function which extracts the key from an element of l."
  112.  
  113. BinarySubsets::usage = "BinarySubsets[l] returns all subsets of l ordered according to the binary string defining each subset."
  114.  
  115. BipartiteMatching::usage = "BipartiteMatching[g] returns the list of edges associated with a maximum matching in bipartite graph g."
  116.  
  117. BipartiteQ::usage = "BipartiteQ[g] returns True if graph g is bipartite."
  118.  
  119. BreadthFirstTraversal::usage = "BreadthFirstTraversal[g,v] performs a breadth-first traversal of graph g starting from vertex v, and returns a list of vertices in the order in which they were encountered."
  120.  
  121. Bridges::usage = "Bridges[g] returns a list of the bridges of graph g, the edges whose removal disconnects the graph."
  122.  
  123. CartesianProduct::usage = "CartesianProduct[l1,l2] returns the Cartesian product of lists l1 and l2."
  124.  
  125. CatalanNumber::usage = "CatalanNumber[n] computes the nth Catalan number, for a positive integer n."
  126.  
  127. ChangeEdges::usage = "ChangeEdges[g,e] constructs a graph with the adjacency matrix e and the embedding of graph g."
  128.  
  129. ChangeVertices::usage = "ChangeVertices[g,v] constructs a graph with the adjacency matrix of graph g and the list v as its embedding."
  130.  
  131. ChromaticNumber::usage = "ChromaticNumber[g] computes the chromatic number of the graph, the fewest number of colors necessary to color the graph."
  132.  
  133. ChromaticPolynomial::usage = "ChromaticPolynomial[g,z] returns the chromatic polynomial P(z) of graph g, which counts the number of ways to color g with exactly z colors."
  134.  
  135. CirculantGraph::usage = "CirculantGraph[n,l] constructs a circulant graph on n vertices, meaning the ith vertex is adjacent to the (i+j)th and (i-j)th vertex, for each j in list l."
  136.  
  137. CircularVertices::usage = "CircularVertices[n] constructs a list of n points equally spaced on a circle."
  138.  
  139. CliqueQ::usage = "CliqueQ[g,c] returns True if the list of vertices c defines a clique in graph g."
  140.  
  141. CodeToLabeledTree::usage = "CodeToLabeledTree[l] constructs the unique labeled tree on n vertices from the Prufer code l, which consists of a list of n-2 integers from 1 to n."
  142.  
  143. Cofactor::usage = "Cofactor[m,{i,j}] calculates the (i,j)th cofactor of matrix m."
  144.  
  145. CompleteQ::usage = "CompleteQ[g] returns True if graph g is complete."
  146.  
  147. Compositions::usage = "Compositions[n,k] returns a list of all compositions of integer n into k parts."
  148.  
  149. ConnectedComponents::usage = "ConnectedComponents[g] returns the vertices of graph g partitioned into connected components."
  150.  
  151. ConnectedQ::usage = "ConnectedQ[g] returns True if undirected graph g is connected. ConnectedQ[g,Directed] and ConnectedQ[g,Undirected] returns True if g is strongly or weakly connected, respectively."
  152.  
  153. ConstructTableau::usage = "ConstructTableau[p] performs the bumping algorithm repeatedly on each element of permutation p, resulting in a distinct Young tableau."
  154.  
  155. Contract::usage = "Contract[g,{x,y}] gives the graph resulting from contracting edge {x,y} of graph g."
  156.  
  157. CostOfPath::usage = "CostOfPath[g,p] sums up the weights of the edges in graph g defined by the path p."
  158.  
  159. Cycle::usage = "Cycle[n] constructs the cycle on n vertices, a 2-regular connected graph."
  160.  
  161. DeBruijnSequence::usage = "DeBruijnSequence[a,n] constructs a de Bruijn sequence on the alphabet described by list a, the shortest sequence such that every string of length n on a occurs as a contiguous subrange of the sequence."
  162.  
  163. DegreeSequence::usage = "DegreeSequence[g] returns the sorted degree sequence of graph g."
  164.  
  165. DeleteCycle::usage = "DeleteCycle[g,c] deletes undirected cycle c from graph g. DeleteCycle[g,c,Directed] deletes directed cycle c from graph g."
  166.  
  167. DeleteEdge::usage = "DeleteEdge[g,{x,y}] returns graph g minus undirected edge {x,y}, while DeleteEdge[g,{x,y},Directed] returns graph g minus directed edge {x,y}."
  168.  
  169. DeleteFromTableau::usage = "DeleteFromTableau[t,r] deletes the last element of row r from Young tableaux t."
  170.  
  171. DeleteVertex::usage = "DeleteVertex[g,v] deletes vertex v from graph g."
  172.  
  173. DepthFirstTraversal::usage = "DepthFirstTraversal[g,v] performs a depth-first traversal of graph g starting from vertex v, and returns a list of vertices in the order in which they were encountered."
  174.  
  175. DerangementQ::usage = "DerangementQ[p] tests whether permutation p is a derangement, a permutation without a fixed point."
  176.  
  177. Derangements::usage = "Derangements[p] constructs all derangements of permutation p."
  178.  
  179. Diameter::usage = "Diameter[g] computes the diameter of graph g, the length of the longest shortest path between two vertices of g."
  180.  
  181. Dijkstra::usage = "Dijkstra[g,v] returns the shortest path spanning tree and associated distances from vertex v of graph g."
  182.  
  183. DilateVertices::usage = "DilateVertices[v,d] multiplies each coordinate of each vertex position in list l by d, thus dilating the embedding."
  184.  
  185. DistinctPermutations::usage = "DistinctPermutations[l] returns all permutations of the multiset described by list l."
  186.  
  187. Distribution::usage = "Distribution[l,set] lists the frequency of occurrence of each element of set in list l."
  188.  
  189. DurfeeSquare::usage = "DurfeeSquare[p] computes the number of rows involved in the Durfee square of partition p, the side of the largest sized square contained within the Ferrers diagram of p."
  190.  
  191. Eccentricity::usage = "Eccentricity[g] computes the eccentricity of each vertex v of graph g, the length of the longest shortest path from v."
  192.  
  193. EdgeChromaticNumber::usage = "EdgeChromaticNumber[g] computes the fewest number of colors necessary to color each edge of graph g, so that no two edges incident on the same vertex have the same color."
  194.  
  195. EdgeColoring::usage = "EdgeColoring[g] uses Brelaz's heuristic to find a good, but not necessarily minimal, edge coloring of graph g."
  196.  
  197. EdgeConnectivity::usage = "EdgeConnectivity[g] computes the minimum number of edges whose deletion from graph g disconnects it."
  198.  
  199. Edges::usage = "Edges[g] returns the adjacency matrix of graph g."
  200.  
  201. Element::usage = "Element[a,l] returns the lth element of nested list a, where l is a list of indices"
  202.  
  203. EmptyGraph::usage = "EmptyGraph[n] generates an empty graph on n vertices."
  204.  
  205. EmptyQ::usage = "EmptyQ[g] returns True if graph g contains no edges."
  206.  
  207. EncroachingListSet::usage = "EncroachingListSet[p] constructs the encroaching list set associated with permutation p."
  208.  
  209. EquivalenceClasses::usage = "EquivalenceClasses[r] identifies the equivalence classes among the elements of matrix r."
  210.  
  211. EquivalenceRelationQ::usage = "EquivalenceRelationQ[r] returns True if the matrix r defines an equivalence relation. EquivalenceRelationQ[g] tests whether the adjacency matrix of graph g defines an equivalence relation."
  212.  
  213. Equivalences::usage = "Equivalences[g,h] lists the vertex equivalence classes between graphs g and h defined by the all-pairs shortest path heuristic."
  214.  
  215. EulerianCycle::usage = "EulerianCycle[g] finds an Eulerian circuit of undirected graph g if one exists. EulerianCycle[g,Directed] finds an Eulerian circuit of directed graph g if one exists."
  216.  
  217. EulerianQ::usage = "EulerianQ[g] returns True if graph g is Eulerian, meaning there exists a tour which includes each edge exactly once. EulerianQ[g,Directed] returns True if directed graph g is Eulerian."
  218.  
  219. Eulerian::usage = "Eulerian[n,k] computes the number of permutations of length n with k runs."
  220.  
  221. ExactRandomGraph::usage = "ExactRandomGraph[n,e] constructs a random labeled graph of exactly e edges and n vertices."
  222.  
  223. ExpandGraph::usage = "ExpandGraph[g,n] expands graph g to n vertices by adding disconnected vertices."
  224.  
  225. ExtractCycles::usage = "ExtractCycles[g] returns a list of edge disjoint cycles in graph g."
  226.  
  227. FerrersDiagram::usage = "FerrersDiagram[p] draws a Ferrers diagram of integer partition p."
  228.  
  229. FindCycle::usage = "FindCycle[g] finds a list of vertices which define an undirected cycle in graph g. FindCycle[g,Directed] finds a directed cycle in graph g."
  230.  
  231. FindSet::usage = "FindSet[n,s] returns the root of the set containing n in union-find data structure s."
  232.  
  233. FirstLexicographicTableau::usage = "FirstLexicographicTableau[p] constructs the first Young tableau with shape described by partition p."
  234.  
  235. FromAdjacencyLists::usage = "FromAdjacencyLists[l] constructs an adjacency matrix representation for a graph with adjacency lists l, using a circular embedding. FromAdjacencyLists[l,v] uses v as the embedding for the resulting graph."
  236.  
  237. FromCycles::usage = "FromCycles[c] restores a cycle structure c to the original permutation."
  238.  
  239. FromInversionVector::usage = "FromInversionVector[v] reconstructs the unique permutation with  inversion vector v."
  240.  
  241. FromOrderedPairs::usage = "FromOrderedPairs[l] constructs an adjacency matrix representation from a list of ordered pairs l, using a circular embedding. FromOrderedPairs[l,v] uses v as the embedding for the resulting graph."
  242.  
  243. FromUnorderedPairs::usage = "FromUnorderedPairs[l] constructs an adjacency matrix representation from a list of unordered pairs l, using a circular embedding. FromUnorderedPairs[l,v] uses v as the embedding for the resulting graph."
  244.  
  245. FunctionalGraph::usage = "FunctionalGraph[f,n] constructs the functional digraph on n vertices defined by integer function f."
  246.  
  247. Girth::usage = "Girth[g] computes the length of the shortest cycle in unweighted graph g."
  248.  
  249. GraphCenter::usage = "GraphCenter[g] returns a list of the vertices of graph g with minimum eccentricity."
  250.  
  251. GraphComplement::usage = "GraphComplement[g] returns the complement of graph g."
  252.  
  253. GraphDifference::usage = "GraphDifference[g,h] constructs the graph resulting from subtracting the adjacency matrix of graph g from that of graph h."
  254.  
  255. GraphIntersection::usage = "GraphIntersection[g,h] constructs the graph defined by the edges which are in both graph g and graph h."
  256.  
  257. GraphJoin::usage = "GraphJoin[g,h] constructs the join of graphs g and h."
  258.  
  259. GraphPower::usage = "GraphPower[g,k] computes the kth power of graph g, meaning there is an edge between any pair of vertices of g with a path between them of length at most k."
  260.  
  261. GraphProduct::usage = "GraphProduct[g,h] constructs the product of graphs g and h."
  262.  
  263. GraphSum::usage = "GraphSum[g,h] constructs the graph resulting from adding the adjacency matrices of graphs g and h."
  264.  
  265. GraphUnion::usage = "GraphUnion[g,h] constructs the union of graphs g and h. GraphUnion[n,g] constructs n copies of graph g, where n is an integer."
  266.  
  267. GraphicQ::usage = "GraphicQ[s] returns True if the list of integers s is graphic, and thus represents a degree sequence of some graph."
  268.  
  269. GrayCode::usage = "GrayCode[l] constructs a binary reflected Gray code on set l."
  270.  
  271. GridGraph::usage = "GridGraph[n,m] constructs an n*m grid graph, the product of paths on n and m vertices."
  272.  
  273. HamiltonianCycle::usage = "HamiltonianCycle[g] finds a Hamiltonian cycle in graph g if one exists. HamiltonianCycle[g,All] returns all Hamiltonian cycles of graph g."
  274.  
  275. HamiltonianQ::usage = "HamiltonianQ[g] returns True if there exists a Hamiltonian cycle in graph g, in other words, if there exists a cycle which visits each vertex exactly once."
  276.  
  277. Harary::usage = "Harary[k,n] constructs the minimal k-connected graph on n vertices."
  278.  
  279. HasseDiagram::usage = "HasseDiagram[g] constructs a Hasse diagram of the relation defined by directed acyclic graph g."
  280.  
  281. HeapSort::usage = "HeapSort[l] performs a heap sort on the items of list l."
  282.  
  283. Heapify::usage = "Heapify[p] builds a heap from permutation p."
  284.  
  285. HideCycles::usage = "HideCycles[c] canonically encodes the cycle structure c into a unique permutation."
  286.  
  287. Hypercube::usage = "Hypercube[n] constructs an n-dimensional hypercube."
  288.  
  289. IdenticalQ::usage = "IdenticalQ[g,h] returns True if graphs g and h have identical adjacency matrices."
  290.  
  291. IncidenceMatrix::usage = "IncidenceMatrix[g] returns the (0,1) incidence matrix of graph g, which has a row for each vertex and column for each edge and (v,e)=1 if and only if vertex v is incident upon edge e."
  292.  
  293. IndependentSetQ::usage = "IndependentSetQ[g,i] returns True if the vertices in list i define an independent set in graph g."
  294.  
  295. Index::usage = "Index[p] returns the index of permutation p, the sum of all subscripts j such that p[j] is greater than p[j+1]."
  296.  
  297. InduceSubgraph::usage = "InduceSubgraph[g,s] constructs the subgraph of graph g induced by the list of vertices s."
  298.  
  299. InitializeUnionFind::usage = "InitializeUnionFind[n] initializes a union-find data structure for n elements."
  300.  
  301. InsertIntoTableau::usage = "InsertIntoTableau[e,t] inserts integer e into Young tableau t using the bumping algorithm."
  302.  
  303. IntervalGraph::usage = "IntervalGraph[l] constructs the interval graph defined by the list of intervals l."
  304.  
  305. InversePermutation::usage = "InversePermutation[p] yields the multiplicative inverse of permutation p."
  306.  
  307. Inversions::usage = "Inversions[p] counts the number of inversions in permutation p."
  308.  
  309. InvolutionQ::usage = "InvolutionQ[p] returns True if permutation p is its own inverse."
  310.  
  311. IsomorphicQ::usage = "IsomorphicQ[g,h] returns True if graphs g and h are isomorphic."
  312.  
  313. IsomorphismQ::usage = "IsomorphismQ[g,h,p] tests if permutation p defines an isomorphism between graphs g and h."
  314.  
  315. Isomorphism::usage = "Isomorphism[g,h] returns an isomorphism between graphs g and h if one exists."
  316.  
  317. Josephus::usage = "Josephus[n,m] generates the inverse of the permutation defined by executing every mth member in a circle of n men."
  318.  
  319. KSubsets::usage = "KSubsets[l,k] returns all subsets of set l containing exactly k elements, ordered lexicographically."
  320.  
  321. K::usage = "K[n] creates a complete graph on n vertices. K[a,b,c,...,k] creates a complete k-partite graph of the prescribed shape."
  322.  
  323. LabeledTreeToCode::usage = "LabeledTreeToCode[g] reduces the tree g to its Prufer code."
  324.  
  325. LastLexicographicTableau::usage = "LastLexicographicTableau[p] constructs the last Young tableau with shape described by partition p."
  326.  
  327. LexicographicPermutations::usage = "LexicographicPermutations[l] constructs all permutations of list l in lexicographic order."
  328.  
  329. LexicographicSubsets::usage = "LexicographicSubsets[l] returns all subsets of set l in lexicographic order."
  330.  
  331. LineGraph::usage = "LineGraph[g] constructs the line graph of graph g."
  332.  
  333. LongestIncreasingSubsequence::usage = "LongestIncreasingSubsequence[p] find the longest increasing scattered subsequence of permutation p."
  334.  
  335. M::usage = "M[g] gives the number of edges in undirected graph g."
  336.  
  337. MakeGraph::usage = "MakeGraph[v,f] constructs the binary relation defined by function f on all pairs of elements of list v."
  338.  
  339. MakeSimple::usage = "MakeSimple[g] returns an undirected, unweighted graph derived from directed graph g."
  340.  
  341. MakeUndirected::usage = "MakeUndirected[g] returns a graph with an undirected edge for each directed edge of graph g."
  342.  
  343. MaximalMatching::usage = "MaximalMatching[g] returns the list of edges associated with a maximal matching of graph g."
  344.  
  345. MaximumAntichain::usage = "MaximumAntichain[g] returns a largest set of unrelated vertices in partial order g."
  346.  
  347. MaximumClique::usage = "MaximumClique[g] finds the largest clique in graph g."
  348.  
  349. MaximumIndependentSet::usage = "MaximumIndependentSet[g] finds the largest independent set of graph g."
  350.  
  351. MaximumSpanningTree::usage = "MaximumSpanningTree[g] uses Kruskal's algorithm to find a maximum spanning tree of graph g."
  352.  
  353. MinimumChainPartition::usage = "MinimumChainPartition[g] partitions partial order g into a minimum number of chains."
  354.  
  355. MinimumChangePermutations::usage = "MinimumChangePermutations[l] constructs all permutations of list l such that adjacent permutations differ by only one transposition."
  356.  
  357. MinimumSpanningTree::usage = "MinimumSpanningTree[g] uses Kruskal's algorithm to find a minimum spanning tree of graph g."
  358.  
  359. MinimumVertexCover::usage = "MinimumVertexCover[g] finds the minimum vertex cover of graph g."
  360.  
  361. MultiplicationTable::usage = "MultiplicationTable[l,f] constructs the complete transition table defined by the binary relation function f on the elements of list l."
  362.  
  363. NetworkFlowEdges::usage = "NetworkFlowEdges[g,source,sink] returns the adjacency matrix showing the distribution of the maximum flow from source to sink in graph g."
  364.  
  365. NetworkFlow::usage = "NetworkFlow[g,source,sink] finds the maximum flow through directed graph g from source to sink."
  366.  
  367. NextComposition::usage = "NextComposition[l] constructs the integer composition which follows l in a canonical order."
  368.  
  369. NextKSubset::usage = "NextKSubset[l,s] computes the k-subset of list l which appears after k-subsets s in lexicographic order."
  370.  
  371. NextPartition::usage = "NextPartition[p] returns the integer partition following p in reverse lexicographic order."
  372.  
  373. NextPermutation::usage = "NextPermutation[p] returns the permutation following p in lexicographic order"
  374.  
  375. NextSubset::usage = "NextSubset[l,s] constructs the subset of l following subset s in canonical order."
  376.  
  377. NextTableau::usage = "NextTableau[t] returns the tableau of shape t which follows t in lexicographic order."
  378.  
  379. NormalizeVertices::usage = "NormalizeVertices[v] returns a list of vertices with the same structure as v but with all coordinates of all points between 0 and 1."
  380.  
  381. NthPair::usage = "NthPair[n] returns the nth unordered pair of positive integers, when sequenced to minimize the size of the larger integer."
  382.  
  383. NthPermutation::usage = "NthPermutation[n,l] returns the nth lexicographic permutation of list l."
  384.  
  385. NthSubset::usage = "NthSubset[n,l] returns the nth subset of list l in canonical order."
  386.  
  387. NumberOfCompositions::usage = "NumberOfCompositions[n,k] counts the number of distinct compositions of  integer n into k parts."
  388.  
  389. NumberOfDerangements::usage = "NumberOfDerangements[n] counts the derangements on n elements, the permutations without any fixed points."
  390.  
  391. NumberOfInvolutions::usage = "NumberOfInvolutions[n] counts the number of involutions on n elements."
  392.  
  393. NumberOfPartitions::usage = "NumberOfPartitions[n] counts the number of distinct integer partitions of n."
  394.  
  395. NumberOfPermutationsByCycles::usage = "NumberOfPermutationsByCycles[n,m] returns the number of permutations of length n with exactly m cycles."
  396.  
  397. NumberOfSpanningTrees::usage = "NumberOfSpanningTrees[g] computes the number of distinct labeled spanning trees of graph g."
  398.  
  399. NumberOfTableaux::usage = "NumberOfTableaux[p] uses the hook length formula to count the number of Young tableaux with shape defined by partition p."
  400.  
  401. OrientGraph::usage = "OrientGraph[g] assigns a direction to each edge of a bridgeless, undirected graph g, so that the graph is strongly connected."
  402.  
  403. PartialOrderQ::usage = "PartialOrderQ[g] returns True if the binary relation defined by the adjacency matrix of graph g is a partial order, meaning it is transitive, reflexive, and anti-symmetric."
  404.  
  405. PartitionQ::usage = "PartitionQ[p] returns True if p is an integer partition."
  406.  
  407. Partitions::usage = "Partitions[n] constructs all partitions of integer n in reverse lexicographic order."
  408.  
  409. PathConditionGraph::usage = "PathConditionGraph[g] replaces each non-edge of a graph by an infinite cost, so shortest path algorithms work correctly"
  410.  
  411. Path::usage = "Path[n] constructs a tree consisting only of a path on n vertices."
  412.  
  413. PerfectQ::usage = "PerfectQ[g] returns true is g is a perfect graph, meaning that for every induced subgraph of g the size of the largest clique equals the chromatic number."
  414.  
  415. PermutationGroupQ::usage = "PermutationGroupQ[l] returns True if the list of permutations l forms a permutation group."
  416.  
  417. PermutationQ::usage = "PermutationQ[p] returns True if p represents a permutation and False otherwise."
  418.  
  419. Permute::usage = "Permute[l,p] permutes list l according to permutation p."
  420.  
  421. PlanarQ::usage = "PlanarQ[g] returns True if graph g is planar, meaning it can be drawn in the plane so no two edges cross."
  422.  
  423. PointsAndLines::usage = "PointsAndLines[g] constructs a partial graphics representation of a graph g."
  424.  
  425. Polya::usage = "Polya[g,m] returns the polynomial giving the number of colorings, with m colors, of a structure defined by the permutation group g."
  426.  
  427. PseudographQ::usage = "PseudographQ[g] returns True if graph g is a pseudograph, meaning it contains self-loops."
  428.  
  429. RadialEmbedding::usage = "RadialEmbedding[g] constructs a radial embedding of graph g, radiating from the center of the graph."
  430.  
  431. Radius::usage = "Radius[g] computes the radius of graph g, the minimum eccentricity of any vertex of g."
  432.  
  433. RandomComposition::usage = "RandomComposition[n,k] constructs a random composition of integer n into k parts."
  434.  
  435. RandomGraph::usage = "RandomGraph[n,p,{l,h}] constructs a random labeled graph on n vertices with an edge probability of p and edge weights of integers drawn uniformly at random from the range (l,h). RandomGraph[n,p,{l,h},Directed] similarly constructs a random directed graph."
  436.  
  437. RandomHeap::usage = "RandomHeap[n] constructs a random heap on n elements."
  438.  
  439. RandomKSubset::usage = "RandomKSubset[l,k] returns a random subset of set l with exactly k elements."
  440.  
  441. RandomPartition::usage = "RandomPartition[n] constructs a random partition of integer n."
  442.  
  443. RandomPermutation1::usage = "RandomPermutation1[n] sorts random numbers to generate a random permutation."
  444.  
  445. RandomPermutation2::usage = "RandomPermutation2[n] uses random transpositions to generate random permutations."
  446.  
  447. RandomPermutation::usage = "RandomPermutation[n] returns a random permutation of length n."
  448.  
  449. RandomSubset::usage = "RandomSubset[l] creates a random subset of set l."
  450.  
  451. RandomTableau::usage = "RandomTableau[p] constructs a random Young tableau of shape p."
  452.  
  453. RandomTree::usage = "RandomTree[n] constructs a random labeled tree on n vertices."
  454.  
  455. RandomVertices::usage = "RandomVertices[g] assigns a random embedding to graph g."
  456.  
  457. RankGraph::usage = "RankGraph[g,l] partitions the vertices into classes based on the shortest geodesic distance to a member of list l."
  458.  
  459. RankPermutation::usage = "RankPermutation[p] computes the rank of permutation p in lexicographic order."
  460.  
  461. RankSubset::usage = "RankSubset[l,s] computes the rank, in canonical order, of subset s of set l."
  462.  
  463. RankedEmbedding::usage = "RankedEmbedding[g,l] performs a ranked embedding of graph g, with the vertices ranked in terms of geodesic distance from a member of list l."
  464.  
  465. ReadGraph::usage = "ReadGraph[f] reads a graph represented as edge lists from file f, and returns the graph as a graph object."
  466.  
  467. RealizeDegreeSequence::usage = "RealizeDegreeSequence[s] constructs a semirandom graph with degree sequence s."
  468.  
  469. RegularGraph::usage = "RegularGraph[k,n] constructs a semirandom k-regular graph on n vertices, if such a graph exists."
  470.  
  471. RegularQ::usage = "RegularQ[g] returns True if g is a regular graph."
  472.  
  473. RemoveSelfLoops::usage = "RemoveSelfLoops[g] constructs a graph g with the same edges except for any self-loops."
  474.  
  475. RevealCycles::usage = "RevealCycles[p] unveils the canonical hidden cycle structure of permutation p."
  476.  
  477. RootedEmbedding::usage = "RootedEmbedding[g,v] constructs a rooted embedding of graph g with vertex v as the root."
  478.  
  479. RotateVertices::usage = "RotateVertices[v,theta] rotates each vertex position in list v by theta radians around the origin (0,0)."
  480.  
  481. Runs::usage = "Runs[p] partitions p into contiguous increasing subsequences."
  482.  
  483. SamenessRelation::usage = "SamenessRelation[l] constructs a binary relation from a list of permutations l which is an equivalence relation if l is a permutation group."
  484.  
  485. SelectionSort::usage = "SelectionSort[l,f] sorts list l using ordering function f."
  486.  
  487. SelfComplementaryQ::usage = "SelfComplementaryQ[g] returns True if graph g is self-complementary, meaning it is isomorphic to its complement."
  488.  
  489. ShakeGraph::usage = "ShakeGraph[g,d] performs a random perturbation of the vertices of graph g, with each vertex moving at most a distance d from its original position."
  490.  
  491. ShortestPathSpanningTree::usage = "ShortestPathSpanningTree[g,v] constructs the shortest-path spanning tree originating from v, so that the shortest path in graph g from v to any other vertex is the path in the tree."
  492.  
  493. ShortestPath::usage = "ShortestPath[g,start,end] finds the shortest path between vertices start and end in graph g."
  494.  
  495. ShowGraph::usage = "ShowGraph[g] displays graph g according to its embedding. ShowGraph[g,Directed] displays directed graph g according to its embedding, with arrows illustrating the orientation of each edge."
  496.  
  497. ShowLabeledGraph::usage = "ShowLabeledGraph[g] displays graph g according to its embedding, with each vertex labeled with its vertex number. ShowLabeledGraph[g,l] uses the ith element of list l as the label for vertex i."
  498.  
  499. SignaturePermutation::usage = "SignaturePermutation[p] gives the signature of permutation p."
  500.  
  501. SimpleQ::usage = "SimpleQ[g] returns True if g is a simple graph, meaning it is unweighted and contains no self-loops."
  502.  
  503. Spectrum::usage = "Spectrum[g] gives the eigenvalues of graph g."
  504.  
  505. SpringEmbedding::usage = "SpringEmbedding[g] beautifies the embedding of graph g by modeling the embedding as a system of springs."
  506.  
  507. StableMarriage::usage = "StableMarriage[mpref,fpref] finds the male optimal stable marriage defined by lists of permutations describing male and female preferences."
  508.  
  509. Star::usage = "Star[n] constructs a star on n vertices, which is a tree with one vertex of degree n-1."
  510.  
  511. StirlingFirst::usage = "StirlingFirst[n,k] computes the Stirling numbers of the first kind."
  512.  
  513. StirlingSecond::usage = "StirlingSecond[n,k] computes the Stirling numbers of the second kind."
  514.  
  515. Strings::usage = "Strings[l,n] constructs all possible strings of length n from the elements of list l."
  516.  
  517. StronglyConnectedComponents::usage = "StronglyConnectedComponents[g] returns the strongly connected components of directed graph g."
  518.  
  519. Subsets::usage = "Subsets[l] returns all subsets of set l."
  520.  
  521. TableauClasses::usage = "TableauClasses[p] partitions the elements of permutation p into classes according to their initial columns during Young tableaux construction."
  522.  
  523. TableauQ::usage = "TableauQ[t] returns True if and only if t represents a Young tableau."
  524.  
  525. TableauxToPermutation::usage = "TableauxToPermutation[t1,t2] constructs the unique permutation associated with Young tableaux t1 and t2, where both tableaux have the same shape. "
  526.  
  527. Tableaux::usage = "Tableaux[p] constructs all tableaux whose shape is given by integer partition p."
  528.  
  529. ToAdjacencyLists::usage = "ToAdjacencyLists[g] constructs an adjacency list representation for graph g."
  530.  
  531. ToCycles::usage = "ToCycles[p] returns the cycle structure of permutation p."
  532.  
  533. ToInversionVector::usage = "ToInversionVector[p] computes the inversion vector associated with permutation p."
  534.  
  535. ToOrderedPairs::usage = "ToOrderedPairs[g] constructs a list of ordered pairs representing the edges of undirected graph g."
  536.  
  537. ToUnorderedPairs::usage = "ToUnorderedPairs[g] constructs a list of vertex pairs representing graph g, with one pair per undirected edge."
  538.  
  539. TopologicalSort::usage = "TopologicalSort[g] returns a permutation of the vertices of directed acyclic graph g such that an edge (i,j) implies vertex i appears before vertex j."
  540.  
  541. TransitiveClosure::usage = "TransitiveClosure[g] finds the transitive closure of graph g, the superset of g which contains edge {x,y} iff there is a path from x to y."
  542.  
  543. TransitiveQ::usage = "TransitiveQ[g] returns True if graph g defines a transitive relation."
  544.  
  545. TransitiveReduction::usage = "TransitiveReduction[g] finds the smallest graph which has the same transitive closure as g."
  546.  
  547. TranslateVertices::usage = "TranslateVertices[v,{x,y}] adds the vector {x,y} to each vertex in list v."
  548.  
  549. TransposePartition::usage = "TransposePartition[p] reflects a partition p of k parts along the main diagonal, creating a partition with maximum part k."
  550.  
  551. TransposeTableau::usage = "TransposeTableau[t] reflects a Young tableau t along the main diagonal, creating a different tableau."
  552.  
  553. TravelingSalesmanBounds::usage = "TravelingSalesmanBounds[g] computes upper and lower bounds on the minimum cost traveling salesman tour of graph g."
  554.  
  555. TravelingSalesman::usage = "TravelingSalesman[g] finds the optimal traveling salesman tour in graph g."
  556.  
  557. TreeQ::usage = "TreeQ[g] returns True if graph g is a tree."
  558.  
  559. TriangleInequalityQ::usage = "TriangleInequalityQ[g] returns True if the weight function defined by the adjacency matrix of graph g satisfies the triangle inequality."
  560.  
  561. Turan::usage = "Turan[n,p] constructs the Turan graph, the extremal graph on n vertices which does not contain K[p]."
  562.  
  563. TwoColoring::usage = "TwoColoring[g] finds a two-coloring of graph g if g is bipartite."
  564.  
  565. UndirectedQ::usage = "UndirectedQ[g] returns True if graph g is undirected."
  566.  
  567. UnionSet::usage = "UnionSet[a,b,s] merges the sets containing a and b in union-find data structure s."
  568.  
  569. UnweightedQ::usage = "UnweightedQ[g] returns True if all entries in the adjacency matrix of graph g are zero or one."
  570.  
  571. V::usage = "V[g] gives the order or number of vertices of graph g."
  572.  
  573. VertexColoring::usage = "VertexColoring[g] uses Brelaz's heuristic to find a good, but not necessarily minimal, vertex coloring of graph g."
  574.  
  575. VertexConnectivity::usage = "VertexConnectivity[g] computes the minimum number of vertices whose deletion from graph g disconnects it."
  576.  
  577. VertexCoverQ::usage = "VertexCoverQ[g,c] returns True if the vertices in list c define a vertex cover of graph g."
  578.  
  579. Vertices::usage = "Vertices[g] returns the embedding of graph g."
  580.  
  581. WeaklyConnectedComponents::usage = "WeaklyConnectedComponents[g] returns the weakly connected components of directed graph g."
  582.  
  583. Wheel::usage = "Wheel[n] constructs a wheel on n vertices, which is the join of K[1] and Cycle[n-1]."
  584.  
  585. WriteGraph::usage = "WriteGraph[g,f] writes graph g to file f using an edge list representation."
  586.  
  587. Begin["`private`"]
  588. PermutationQ[p_List] := (Sort[p] == Range[Length[p]])
  589.  
  590. Permute[l_List,p_?PermutationQ] := l [[ p ]]
  591.  
  592. LexicographicPermutations[{l_}] := {{l}}
  593.  
  594. LexicographicPermutations[{a_,b_}] := {{a,b},{b,a}}
  595.  
  596. LexicographicPermutations[l_List] :=
  597.     Module[{i,n=Length[l]},
  598.         Apply[
  599.             Join,
  600.             Table[ 
  601.                 Map[
  602.                     (Prepend[#,l[[i]]])&,
  603.                     LexicographicPermutations[
  604.                         Complement[l,{l[[i]]}]
  605.                     ]
  606.                 ],
  607.                 {i,n}
  608.             ]
  609.         ]
  610.     ]
  611.  
  612. RankPermutation[{1}] = 0
  613.  
  614. RankPermutation[p_?PermutationQ] := (p[[1]]-1) (Length[Rest[p]]!) +
  615.     RankPermutation[ Map[(If[#>p[[1]], #-1, #])&, Rest[p]] ]
  616.  
  617. NthPermutation[n1_Integer,l_List] :=
  618.     Module[{k, n=n1, s=l, i},
  619.         Table[
  620.             n = Mod[n,(i+1)!];
  621.             k = s [[Quotient[n,i!]+1]];
  622.             s = Complement[s,{k}];
  623.             k,
  624.             {i,Length[l]-1,0,-1}
  625.         ]
  626.     ]
  627.  
  628. NextPermutation[p_?PermutationQ] :=
  629.     NthPermutation[ RankPermutation[p]+1, Sort[p] ]
  630.  
  631. RandomPermutation1[n_Integer?Positive] :=
  632.     Map[ Last, Sort[ Map[({Random[],#})&,Range[n]] ] ]
  633.  
  634. RandomPermutation2[n_Integer?Positive] :=
  635.     Module[{p = Range[n],i,x},
  636.         Do [
  637.             x = Random[Integer,{1,i}];
  638.             {p[[i]],p[[x]]} = {p[[x]],p[[i]]},
  639.             {i,n,2,-1}
  640.         ];
  641.         p
  642.     ]
  643.  
  644. RandomPermutation[n_Integer?Positive] := RandomPermutation1[n]
  645.  
  646. MinimumChangePermutations[l_List] :=
  647.     Module[{i=1,c,p=l,n=Length[l],k},
  648.         c = Table[1,{n}];
  649.         Join[
  650.             {l},
  651.             Table[
  652.                 While [ c[[i]] >= i, c[[i]] = 1; i++];
  653.                 If[OddQ[i], k=1, k=c[[i]] ];
  654.                 {p[[i]],p[[k]]} = {p[[k]],p[[i]]};
  655.                 c[[i]]++;
  656.                 i = 2;
  657.                 p,
  658.                 {n!-1}
  659.             ]
  660.         ]
  661.     ]
  662.  
  663. Backtrack[space_List,partialQ_,solutionQ_,flag_:One] :=
  664.     Module[{n=Length[space],all={},done,index,v=2,solution},
  665.         index=Prepend[ Table[0,{n-1}],1];
  666.         While[v > 0,
  667.             done = False;
  668.             While[!done && (index[[v]] < Length[space[[v]]]),
  669.                 index[[v]]++;
  670.                 done = Apply[partialQ,{Solution[space,index,v]}];
  671.             ];
  672.             If [done, v++, index[[v--]]=0 ];
  673.             If [v > n,
  674.                 solution = Solution[space,index,n];
  675.                 If [Apply[solutionQ,{solution}],
  676.                     If [SameQ[flag,All],
  677.                         AppendTo[all,solution],
  678.                         all = solution; v=0
  679.                     ]
  680.                 ];
  681.                 v--
  682.             ]
  683.         ];
  684.         all
  685.     ]
  686.  
  687. Solution[space_List,index_List,count_Integer] :=
  688.     Module[{i}, Table[space[[ i,index[[i]] ]], {i,count}] ]
  689.  
  690. DistinctPermutations[s_List] :=
  691.     Module[{freq,alph=Union[s],n=Length[s]},
  692.         freq = Map[ (Count[s,#])&, alph];
  693.         Map[
  694.             (alph[[#]])&,
  695.             Backtrack[
  696.                 Table[Range[Length[alph]],{n}],
  697.                 (Count[#,Last[#]] <= freq[[Last[#]]])&,
  698.                 (Count[#,Last[#]] <= freq[[Last[#]]])&,
  699.                 All
  700.             ]
  701.         ]
  702.     ]
  703.  
  704. MinOp[l_List,f_] :=
  705.     Module[{min=First[l]},
  706.         Scan[ (If[ Apply[f,{#,min}], min = #])&, l];
  707.         Return[min];
  708.     ]
  709.  
  710. SelectionSort[l_List,f_] :=
  711.     Module[{where,item,unsorted=l},
  712.         Table[
  713.             item = MinOp[unsorted, f];
  714.             {where} = First[ Position[unsorted,item] ];
  715.             unsorted = Drop[unsorted,{where,where}];
  716.             item,
  717.             {Length[l]}
  718.         ]
  719.     ]
  720.  
  721. BinarySearch[l_List,k_Integer] := BinarySearch[l,k,1,Length[l],Identity]
  722. BinarySearch[l_List,k_Integer,f_] := BinarySearch[l,k,1,Length[l],f]
  723.     
  724. BinarySearch[l_List,k_Integer,low_Integer,high_Integer,f_] :=
  725.     Module[{mid = Floor[ (low + high)/2 ]},
  726.         If [low > high, Return[low - 1/2]];
  727.         If [f[ l[[mid]] ] == k, Return[mid]];
  728.         If [f[ l[[mid]] ] > k,
  729.             BinarySearch[l,k,1,mid-1,f],
  730.             BinarySearch[l,k,mid+1,high,f]
  731.         ]
  732.     ]
  733.  
  734. MultiplicationTable[elems_List,op_] :=
  735.     Module[{i,j,n=Length[elems],p},
  736.         Table[
  737.             p = Position[elems, Apply[op,{elems[[i]],elems[[j]]}]];
  738.             If [p === {}, 0, p[[1,1]]],
  739.             {i,n},{j,n}
  740.         ]
  741.     ]
  742.  
  743. InversePermutation[p_?PermutationQ] :=
  744.     Module[{inverse=p, i},
  745.         Do[ inverse[[ p[[i]] ]] = i, {i,Length[p]} ];
  746.         inverse
  747.     ]
  748.  
  749. EquivalenceRelationQ[r_?SquareMatrixQ] :=
  750.     ReflexiveQ[r] && SymmetricQ[r] && TransitiveQ[r]
  751. EquivalenceRelationQ[g_Graph] := EquivalenceRelationQ[ Edges[g] ]
  752.  
  753. SquareMatrixQ[{}] = True
  754. SquareMatrixQ[r_] := MatrixQ[r] && (Length[r] == Length[r[[1]]])
  755.  
  756. ReflexiveQ[r_?SquareMatrixQ] := 
  757.     Module[{i}, Apply[And, Table[(r[[i,i]]!=0),{i,Length[r]}] ] ]
  758.  
  759. TransitiveQ[r_?SquareMatrixQ] := TransitiveQ[ Graph[r,RandomVertices[Length[r]]] ]
  760. TransitiveQ[r_Graph] := IdenticalQ[r,TransitiveClosure[r]]
  761.  
  762. SymmetricQ[r_?SquareMatrixQ] := (r === Transpose[r])
  763.  
  764. EquivalenceClasses[r_List?EquivalenceRelationQ] :=
  765.     ConnectedComponents[ Graph[r,RandomVertices[Length[r]]] ]
  766. EquivalenceClasses[g_Graph?EquivalenceRelationQ] := ConnectedComponents[g]
  767.  
  768. PermutationGroupQ[perms_List] :=
  769.     FreeQ[ MultiplicationTable[perms,Permute], 0] &&
  770.         EquivalenceRelationQ[SamenessRelation[perms]]
  771.  
  772. SamenessRelation[perms_List] :=
  773.     Module[{positions = Transpose[perms], i, j, n=Length[First[perms]]},
  774.         Table[
  775.             If[ MemberQ[positions[[i]],j], 1, 0],
  776.             {i,n}, {j,n}
  777.         ]
  778.     ] /; perms != {}
  779.  
  780. ToCycles[p1_?PermutationQ] :=
  781.     Module[{p=p1,m,n,cycle,i},
  782.         Select[
  783.             Table[
  784.                 m = n = p[[i]];
  785.                 cycle = {};
  786.                 While[ p[[n]] != 0,
  787.                     AppendTo[cycle,m=n];
  788.                     n = p[[n]];
  789.                     p[[m]] = 0 
  790.                 ];
  791.                 cycle,
  792.                 {i,Length[p]}
  793.             ],
  794.             (# =!= {})&
  795.         ]
  796.     ]
  797.  
  798. FromCycles[cyc_List] := 
  799.     Module[{p=Table[0,{Length[Flatten[cyc]]}], pos},
  800.         Scan[
  801.             (pos = Last[#];
  802.              Scan[ Function[c, pos = p[[pos]] = c], #])&,
  803.             cyc
  804.         ];
  805.         p
  806.     ]
  807.  
  808. HideCycles[c_List] := 
  809.     Flatten[
  810.         Sort[
  811.             Map[(RotateLeft[#,Position[#,Min[#]] [[1,1]] - 1])&, c],
  812.             (#1[[1]] > #2[[1]])&
  813.         ]
  814.     ]
  815.  
  816. RevealCycles[p_?PermutationQ] :=
  817.     Module[{start=end=1, cycles={}},
  818.         While [end <= Length[p],
  819.             If [p[[start]] > p[[end]],
  820.                 AppendTo[ cycles, Take[p,{start,end-1}] ];
  821.                 start = end,
  822.                 end++
  823.             ]
  824.         ];
  825.         Append[cycles,Take[p,{start,end-1}]]
  826.     ]
  827.  
  828. NumberOfPermutationsByCycles[n_Integer,m_Integer] := (-1)^(n-m) StirlingS1[n,m]
  829.  
  830. StirlingFirst[n_Integer,m_Integer] := StirlingFirst1[n,m]
  831.  
  832. StirlingFirst1[n_Integer,0] := If [n == 0, 1, 0] 
  833. StirlingFirst1[0,m_Integer] := If [m == 0, 1, 0]
  834.  
  835. StirlingFirst1[n_Integer,m_Integer] := StirlingFirst1[n,m] =
  836.     (n-1) StirlingFirst1[n-1,m] + StirlingFirst1[n-1, m-1]
  837.  
  838. StirlingSecond[n_Integer,m_Integer] := StirlingSecond1[n,m]
  839.  
  840. StirlingSecond1[n_Integer,0] := If [n == 0, 1, 0]
  841. StirlingSecond1[0,m_Integer] := If [m == 0, 1, 0]
  842.  
  843. StirlingSecond1[n_Integer,m_Integer] := StirlingSecond1[n,m] =
  844.     m StirlingSecond1[n-1,m] + StirlingSecond1[n-1,m-1]
  845.  
  846. SignaturePermutation[p_?PermutationQ] := (-1) ^ (Length[p]-Length[ToCycles[p]])
  847.  
  848. Polya[g_List,m_] := Apply[ Plus, Map[(m^Length[ToCycles[#]])&,g] ] / Length[g]
  849.  
  850. ToInversionVector[p_?PermutationQ] :=
  851.     Module[{i,inverse=InversePermutation[p]},
  852.         Table[
  853.             Length[ Select[Take[p,inverse[[i]]], (# > i)&] ],
  854.             {i,Length[p]-1}
  855.         ]
  856.     ]
  857.  
  858. FromInversionVector[vec_List] :=
  859.     Module[{n=Length[vec]+1,i,p},
  860.         p={n};
  861.         Do [
  862.             p = Insert[p, i, vec[[i]]+1],
  863.             {i,n-1,1,-1}
  864.         ];
  865.         p
  866.     ]
  867.  
  868. Inversions[p_?PermutationQ] := Apply[Plus,ToInversionVector[p]]
  869.  
  870. Index[p_?PermutationQ]:=
  871.     Module[{i},
  872.         Sum[ If [p[[i]] > p[[i+1]], i, 0], {i,Length[p]-1} ]
  873.     ]
  874.  
  875. Runs[p_?PermutationQ] :=
  876.     Map[
  877.         (Apply[Take,{p,{#[[1]]+1,#[[2]]}}])&,
  878.         Partition[
  879.             Join[
  880.                 {0},
  881.                 Select[Range[Length[p]-1], (p[[#]]>p[[#+1]])&],
  882.                 {Length[p]}
  883.             ],
  884.             2,
  885.             1
  886.         ]
  887.     ]
  888.  
  889. Eulerian[n_Integer,k_Integer] := Eulerian1[n,k]
  890.  
  891. Eulerian1[0,k_Integer] := If [k==1, 1, 0]
  892. Eulerian1[n_Integer,k_Integer] := Eulerian1[n,k] =
  893.     k Eulerian1[n-1,k] + (n-k+1) Eulerian1[n-1,k-1]
  894.  
  895. InvolutionQ[p_?PermutationQ] := p[[p]] == Range[Length[p]]
  896.  
  897. NumberOfInvolutions[n_Integer] :=
  898.     Module[{k},
  899.         n! Sum[1/((n - 2k)! 2^k k!), {k, 0, Quotient[n, 2]}]
  900.     ]
  901.  
  902. DerangementQ[p_?PermutationQ] :=
  903.     !(Apply[ Or, Map[( # == p[[#]] )&, Range[Length[p]]] ])
  904.  
  905. NumberOfDerangements[0] = 1;
  906. NumberOfDerangements[n_] := n * NumberOfDerangements[n-1] + (-1)^n
  907.  
  908. Derangements[n_Integer] := Derangements[Range[n]]
  909. Derangements[p_?PermutationQ] := Select[ Permutations[p], DerangementQ ]
  910.  
  911. Josephus[n_Integer,m_Integer] :=
  912.     Module[{live=Range[n],next},
  913.         InversePermutation[
  914.             Table[
  915.                 next = RotateLeft[live,m-1];
  916.                 live = Rest[next];
  917.                 First[next],
  918.                 {n}
  919.             ]
  920.         ]
  921.     ]
  922.  
  923. Heapify[p_List] :=
  924.     Module[{j,heap=p},
  925.         Do [
  926.             heap = Heapify[heap,j],
  927.             {j,Quotient[Length[p],2],1,-1}
  928.         ];
  929.         heap
  930.     ]
  931.  
  932. Heapify[p_List, k_Integer] :=
  933.     Module[{hp=p, i=k, l, n=Length[p]},
  934.         While[ (l = 2 i) <= n,
  935.             If[ (l < n) && (hp[[l]] > hp[[l+1]]), l++ ];
  936.             If[ hp[[i]] > hp[[l]],
  937.                 {hp[[i]],hp[[l]]}={hp[[l]],hp[[i]]};
  938.                 i = l,
  939.                 i = n+1
  940.             ];
  941.         ];
  942.         hp
  943.     ]
  944.  
  945. RandomHeap[n_Integer] := Heapify[RandomPermutation[n]]
  946.  
  947. HeapSort[p_List] :=
  948.     Module[{heap=Heapify[p],min},
  949.         Append[
  950.             Table[
  951.                 min = First[heap];
  952.                 heap[[1]] = heap[[n]];
  953.                 heap = Heapify[Drop[heap,-1],1];
  954.                 min,
  955.                 {n,Length[p],2,-1}
  956.             ],
  957.             Max[heap]
  958.         ]
  959.     ]
  960.  
  961. Strings[l_List,0] := { {} }
  962.  
  963. Strings[l_List,k_Integer?Positive] :=
  964.     Module[{oneless = Strings[l,k-1],i,n=Length[l]},
  965.         Apply[Join, Table[ Map[(Prepend[#,l[[i]]])&, oneless], {i,n}] ]
  966.     ]
  967.  
  968. NthSubset[n_Integer,m_Integer] := NthSubset[n,Range[m]]
  969. NthSubset[n_Integer,l_List] :=
  970.     l[[ Flatten[ Position[Reverse[IntegerDigits[ Mod[n,2^Length[l]],2]],1] ] ]]
  971.  
  972. BinarySubsets[l_List] :=
  973.     Module[{pos=Reverse[Range[Length[l]]], n=Length[l]},
  974.         Map[(l[[ Reverse[Select[pos*#, Positive]] ]])&, Strings[{0,1},n] ]
  975.     ]
  976.  
  977. NextSubset[set_List,subset_List] := NthSubset[ RankSubset[set,subset], set  ]
  978.  
  979. RankSubset[set_List,subset_List] :=
  980.     Module[{i,n=Length[set]},
  981.         Sum[ 2^(i-1) * If[ MemberQ[subset,set[[i]]], 1, 0], {i,n}]
  982.     ]
  983.  
  984. RandomSubset[set_List] := NthSubset[Random[Integer,2^(Length[set])-1],set]
  985.  
  986. GrayCode[l_List] := GrayCode[l,{{}}]
  987.  
  988. GrayCode[{},prev_List] := prev
  989.  
  990. GrayCode[l_List,prev_List] :=
  991.     GrayCode[
  992.         Rest[l],
  993.         Join[ prev, Map[(Append[#,First[l]])&,Reverse[prev]] ]
  994.     ]
  995.  
  996. Subsets[l_List] := GrayCode[l]
  997. Subsets[n_Integer] := GrayCode[Range[n]]
  998.  
  999. LexicographicSubsets[l_List] := LexicographicSubsets[l,{{}}]
  1000.  
  1001. LexicographicSubsets[{},s_List] := s
  1002.  
  1003. LexicographicSubsets[l_List,subsets_List] :=
  1004.     LexicographicSubsets[
  1005.         Rest[l],
  1006.         Join[
  1007.             subsets,
  1008.             Map[(Prepend[#,First[l]])&,LexicographicSubsets[Rest[l],{{}}] ]
  1009.         ]
  1010.     ]
  1011.  
  1012. KSubsets[l_List,0] := { {} }
  1013. KSubsets[l_List,1] := Partition[l,1]
  1014. KSubsets[l_List,k_Integer?Positive] := {l} /; (k == Length[l])
  1015. KSubsets[l_List,k_Integer?Positive] := {}  /; (k > Length[l])
  1016.  
  1017. KSubsets[l_List,k_Integer?Positive] :=
  1018.     Join[
  1019.         Map[(Prepend[#,First[l]])&, KSubsets[Rest[l],k-1]],
  1020.         KSubsets[Rest[l],k]
  1021.     ]
  1022.  
  1023. NextKSubset[set_List,subset_List] :=
  1024.     Take[set,Length[subset]] /; (Take[set,-Length[subset]] === subset)
  1025.  
  1026. NextKSubset[set_List,subset_List] :=
  1027.     Module[{h=1, x=1},
  1028.         While [set[[-h]] == subset[[-h]], h++];
  1029.         While [set[[x]] =!= subset[[-h]], x++];
  1030.         Join[ Drop[subset,-h], Take[set, {x+1,x+h}] ]
  1031.     ]
  1032.  
  1033. RandomKSubset[n_Integer,k_Integer] := RandomKSubset[Range[n],k]
  1034.  
  1035. RandomKSubset[set_List,k_Integer] := 
  1036.     Module[{s=Range[Length[set]],i,n=Length[set],x},
  1037.         set [[
  1038.             Sort[
  1039.                 Table[
  1040.                     x=Random[Integer,{1,i}];
  1041.                     {s[[i]],s[[x]]} = {s[[x]],s[[i]]};
  1042.                     s[[i]],
  1043.                     {i,n,n-k+1,-1}
  1044.                 ]
  1045.             ]
  1046.         ]]
  1047.     ]
  1048.  
  1049. PartitionQ[p_List] := (Min[p]>0) && Apply[And, Map[IntegerQ,p]]
  1050.  
  1051. Partitions[n_Integer] := Partitions[n,n]
  1052.  
  1053. Partitions[n_Integer,_] := {} /; (n<0)
  1054. Partitions[0,_] := { {} }
  1055. Partitions[n_Integer,1] := { Table[1,{n}] }
  1056. Partitions[_,0] := {}
  1057.  
  1058. Partitions[n_Integer,maxpart_Integer] :=
  1059.     Join[
  1060.         Map[(Prepend[#,maxpart])&, Partitions[n-maxpart,maxpart]],
  1061.         Partitions[n,maxpart-1]
  1062.     ]
  1063.  
  1064. NextPartition[p_List] := Join[Drop[p,-1],{Last[p]-1,1}]  /; (Last[p] > 1)
  1065.  
  1066. NextPartition[p_List] := {Apply[Plus,p]}  /; (Max[p] == 1)
  1067.  
  1068. NextPartition[p_List] :=
  1069.     Module[{index,k,m},
  1070.         {index} = First[ Position[p,1] ];
  1071.         k = p[[index-1]] - 1;
  1072.         m = Apply[Plus,Drop[p,index-1]] + k + 1;
  1073.         Join[
  1074.             Take[p,index-2],
  1075.             Table[k,{Quotient[m,k]}],
  1076.             If [Mod[m,k] == 0, {}, {Mod[m,k]}]
  1077.         ]
  1078.     ]
  1079.  
  1080. FerrersDiagram[p1_List] :=
  1081.     Module[{i,j,n=Length[p1],p=Sort[p1]},
  1082.         Show[
  1083.             Graphics[
  1084.                 Join[
  1085.                     {PointSize[ Min[0.05,1/(2 Max[p])] ]},
  1086.                     Table[Point[{i,j}], {j,n}, {i,p[[j]]}]
  1087.                 ],
  1088.                 {AspectRatio -> 1, PlotRange -> All}
  1089.             ]
  1090.         ]
  1091.     ]
  1092.  
  1093. TransposePartition[p_List] :=
  1094.     Module[{s=Select[p,(#>0)&], i, row, r},
  1095.         row = Length[s];
  1096.         Table [
  1097.             r = row;
  1098.             While [s[[row]]<=i, row--];
  1099.             r,
  1100.             {i,First[s]}
  1101.         ]
  1102.     ]
  1103.  
  1104. DurfeeSquare[s_List] :=
  1105.     Module[{i,max=1},
  1106.         Do [
  1107.             If [s[[i]] >= i, max=i],
  1108.             {i,2,Min[Length[s],First[s]]}
  1109.         ];
  1110.         max
  1111.     ]
  1112.  
  1113. DurfeeSquare[{}] := 0
  1114.  
  1115. NumberOfPartitions[n_Integer] := NumberOfPartitions1[n]
  1116.  
  1117. NumberOfPartitions1[n_Integer] := 0  /; (n < 0)
  1118. NumberOfPartitions1[n_Integer] := 1  /; (n == 0)
  1119.  
  1120. NumberOfPartitions1[n_Integer] := NumberOfPartitions1[n] =
  1121.     Module[{m},
  1122.         Sum[ (-1)^(m+1) NumberOfPartitions1[n - m (3m-1)/2] +
  1123.             (-1)^(m+1) NumberOfPartitions1[n - m (3m+1)/2],
  1124.             {m, Ceiling[ (1+Sqrt[1.0 + 24n])/6 ], 1, -1}
  1125.         ]
  1126.     ]
  1127.  
  1128. RandomPartition[n_Integer?Positive] :=
  1129.     Module[{mult = Table[0,{n}],j,d,m = n},
  1130.         While[ m != 0,
  1131.             {j,d} = NextPartitionElement[m];
  1132.             m -= j d;
  1133.             mult[[d]] += j;
  1134.         ];
  1135.         Flatten[Map[(Table[#,{mult[[#]]}])&,Reverse[Range[n]]]]
  1136.     ]
  1137.  
  1138. NextPartitionElement[n_Integer] :=
  1139.     Module[{d=0,j,m,z=Random[] n PartitionsP[n],done=False,flag},
  1140.         While[!done,
  1141.             d++; m = n; j = 0; flag = False;
  1142.             While[ !flag,
  1143.                 j++; m -=d;
  1144.                 If[ m > 0, 
  1145.                     z -= d PartitionsP[m];
  1146.                     If[ z <= 0, flag=done=True],
  1147.                     flag = True;
  1148.                     If[m==0, z -=d; If[z <= 0, done = True]]
  1149.                 ];
  1150.             ];
  1151.         ];
  1152.         {j,d}
  1153.     ]
  1154.  
  1155. NumberOfCompositions[n_,k_] := Binomial[ n+k-1, n ]
  1156.  
  1157. RandomComposition[n_Integer,k_Integer] :=
  1158.     Map[
  1159.         (#[[2]] - #[[1]] - 1)&,
  1160.         Partition[Join[{0},RandomKSubset[Range[n+k-1],k-1],{n+k}], 2, 1]
  1161.     ]
  1162.  
  1163. Compositions[n_Integer,k_Integer] :=
  1164.     Map[
  1165.         (Map[(#[[2]]-#[[1]]-1)&, Partition[Join[{0},#,{n+k}],2,1] ])&,
  1166.         KSubsets[Range[n+k-1],k-1]
  1167.     ]
  1168.  
  1169. NextComposition[l_List] := 
  1170.     Module[{c=l, h=1, t},
  1171.         While[c[[h]] == 0, h++];
  1172.         {t,c[[h]]} = {c[[h]],0};
  1173.         c[[1]] = t - 1;
  1174.         c[[h+1]]++;
  1175.         c
  1176.     ]
  1177.  
  1178. NextComposition[l_List] :=
  1179.     Join[{Apply[Plus,l]},Table[0,{Length[l]-1}]] /; Last[l]==Apply[Plus,l]
  1180.  
  1181. TableauQ[{}] = True
  1182. TableauQ[t_List] :=
  1183.     And [
  1184.         Apply[ And, Map[(Apply[LessEqual,#])&,t] ],
  1185.         Apply[ And, Map[(Apply[LessEqual,#])&,TransposeTableau[t]] ],
  1186.         Apply[ GreaterEqual, Map[Length,t] ],
  1187.         Apply[ GreaterEqual, Map[Length,TransposeTableau[t]] ]
  1188.     ]
  1189.  
  1190. TransposeTableau[tb_List] :=
  1191.     Module[{t=Select[tb,(Length[#]>=1)&],row},
  1192.         Table[
  1193.             row = Map[First,t];
  1194.             t = Map[ Rest, Select[t,(Length[#]>1)&] ];
  1195.             row,
  1196.             {Length[First[tb]]}
  1197.         ]
  1198.     ]
  1199.  
  1200. ShapeOfTableau[t_List] := Map[Length,t]
  1201.  
  1202. InsertIntoTableau[e_Integer,{}] := { {e} }
  1203.  
  1204. InsertIntoTableau[e_Integer, t1_?TableauQ] :=
  1205.     Module[{item=e,row=0,col,t=t1},
  1206.         While [row < Length[t],
  1207.             row++;
  1208.             If [Last[t[[row]]] <= item,
  1209.                 AppendTo[t[[row]],item];
  1210.                 Return[t]
  1211.             ];
  1212.             col = Ceiling[ BinarySearch[t[[row]],item] ];
  1213.             {item, t[[row,col]]} = {t[[row,col]], item};
  1214.         ];
  1215.         Append[t, {item}]
  1216.     ]
  1217.  
  1218. ConstructTableau[p_List] := ConstructTableau[p,{}]
  1219.  
  1220. ConstructTableau[{},t_List] := t
  1221.  
  1222. ConstructTableau[p_List,t_List] :=
  1223.     ConstructTableau[Rest[p], InsertIntoTableau[First[p],t]]
  1224.  
  1225. DeleteFromTableau[t1_?TableauQ,r_Integer]:=
  1226.     Module [{t=t1, col, row, item=Last[t1[[r]]]},
  1227.         col = Length[t[[r]]];
  1228.         If[col == 1, t = Drop[t,-1], t[[r]] = Drop[t[[r]],-1]];
  1229.         Do [
  1230.             While [t[[row,col]]<=item && Length[t[[row]]]>col, col++];
  1231.             If [item < t[[row,col]], col--];
  1232.             {item,t[[row,col]]} = {t[[row,col]],item},
  1233.             {row,r-1,1,-1}
  1234.         ];
  1235.         t
  1236.     ]
  1237.  
  1238. TableauxToPermutation[p1_?TableauQ,q1_?TableauQ] :=
  1239.     Module[{p=p1, q=q1, row, firstrow},
  1240.         Reverse[
  1241.             Table[
  1242.                 firstrow = First[p];
  1243.                 row = Position[q, Max[q]] [[1,1]];
  1244.                 p = DeleteFromTableau[p,row];
  1245.                 q[[row]] = Drop[ q[[row]], -1];
  1246.                 If[ p == {},
  1247.                     First[firstrow],
  1248.                     First[Complement[firstrow,First[p]]]
  1249.                 ],
  1250.                 {Apply[Plus,ShapeOfTableau[p1]]}
  1251.             ]
  1252.         ]
  1253.     ] /; ShapeOfTableau[p1] === ShapeOfTableau[q1]
  1254.  
  1255. LastLexicographicTableau[s_List] :=
  1256.     Module[{c=0},
  1257.         Map[(c+=#; Range[c-#+1,c])&, s]
  1258.     ]
  1259.  
  1260. FirstLexicographicTableau[s_List] :=
  1261.     TransposeTableau[ LastLexicographicTableau[ TransposePartition[s] ] ]
  1262.  
  1263. NextTableau[t_?TableauQ] :=
  1264.     Module[{s,y,row,j,count=0,tj,i,n=Max[t]},
  1265.         y = TableauToYVector[t];
  1266.         For [j=2, (j<n)  && (y[[j]]>=y[[j-1]]), j++, ];
  1267.         If [y[[j]] >= y[[j-1]],
  1268.             Return[ FirstLexicographicTableau[ ShapeOfTableau[t] ] ]
  1269.         ];
  1270.         s = ShapeOfTableau[ Table[Select[t[[i]],(#<=j)&], {i,Length[t]}] ];
  1271.         {row} = Last[ Position[ s, s[[ Position[t,j] [[1,1]] + 1 ]] ] ];
  1272.         s[[row]] --;
  1273.         tj = FirstLexicographicTableau[s];
  1274.         If[ Length[tj] < row,
  1275.             tj = Append[tj,{j}],
  1276.             tj[[row]] = Append[tj[[row]],j]
  1277.         ];
  1278.         Join[
  1279.             Table[
  1280.                 Join[tj[[i]],Select[t[[i]],(#>j)&]],
  1281.                 {i,Length[tj]}
  1282.             ],
  1283.             Table[t[[i]],{i,Length[tj]+1,Length[t]}]
  1284.         ]
  1285.     ]
  1286.  
  1287. Tableaux[s_List] :=
  1288.     Module[{t = LastLexicographicTableau[s]},
  1289.         Table[ t = NextTableau[t], {NumberOfTableaux[s]} ]
  1290.     ]
  1291.  
  1292. Tableaux[n_Integer?Positive] := Apply[ Join, Map[ Tableaux, Partitions[n] ] ]
  1293.  
  1294. YVectorToTableau[y_List] :=
  1295.     Module[{k},
  1296.         Table[ Flatten[Position[y,k]], {k,Length[Union[y]]}]
  1297.     ]
  1298.  
  1299. TableauToYVector[t_?TableauQ] :=
  1300.     Module[{i,y=Table[1,{Length[Flatten[t]]}]},
  1301.         Do [ Scan[ (y[[#]]=i)&, t[[i]] ], {i,2,Length[t]} ];
  1302.         y
  1303.     ]
  1304.  
  1305. NumberOfTableaux[{}] := 1
  1306. NumberOfTableaux[s_List] := 
  1307.     Module[{row,col,transpose=TransposePartition[s]},
  1308.         (Apply[Plus,s])! /
  1309.         Product [
  1310.             (transpose[[col]]-row+s[[row]]-col+1),
  1311.             {row,Length[s]}, {col,s[[row]]}
  1312.         ]
  1313.     ]
  1314.  
  1315. NumberOfTableaux[n_Integer] := Apply[Plus, Map[NumberOfTableaux, Partitions[n]]]
  1316.  
  1317. CatalanNumber[n_] := Binomial[2n,n]/(n+1)    /; (n>=0)
  1318.  
  1319. RandomTableau[shape_List] :=
  1320.     Module[{i=j=n=Apply[Plus,shape],done,l,m,h=1,k,y,p=shape},
  1321.         y= Join[TransposePartition[shape],Table[0,{n - Max[shape]}]];
  1322.         Do[
  1323.             {i,j} = RandomSquare[y,p]; done = False;
  1324.             While [!done,
  1325.                 h = y[[j]] + p[[i]] - i - j;
  1326.                 If[ h != 0,
  1327.                     If[ Random[] < 0.5,
  1328.                         j = Random[Integer,{j,p[[i]]}],
  1329.                         i = Random[Integer,{i,y[[j]]}]
  1330.                     ],
  1331.                     done = True
  1332.                 ];
  1333.             ];
  1334.             p[[i]]--; y[[j]]--;
  1335.             y[[m]] = i,
  1336.             {m,n,1,-1}
  1337.         ];
  1338.         YVectorToTableau[y]
  1339.     ]
  1340.  
  1341. RandomSquare[y_List,p_List] :=
  1342.     Module[{i=Random[Integer,{1,First[y]}], j=Random[Integer,{1,First[p]}]},
  1343.         While[(i > y[[j]]) || (j > p[[i]]), 
  1344.             i = Random[Integer,{1,First[y]}];
  1345.             j = Random[Integer,{1,First[p]}]
  1346.         ];
  1347.         {i,j}
  1348.     ]
  1349.  
  1350. TableauClasses[p_?PermutationQ] :=
  1351.     Module[{classes=Table[{},{Length[p]}],t={}},
  1352.         Scan [
  1353.             (t = InsertIntoTableau[#,t];
  1354.              PrependTo[classes[[Position[First[t],#] [[1,1]] ]], #])&,
  1355.             p
  1356.         ];
  1357.         Select[classes, (# != {})&]
  1358.     ]
  1359.  
  1360. LongestIncreasingSubsequence[p_?PermutationQ] :=
  1361.     Module[{c,x,xlast},
  1362.         c = TableauClasses[p];
  1363.         xlast = x = First[ Last[c] ];
  1364.         Append[
  1365.             Reverse[
  1366.                 Map[
  1367.                     (x = First[ Intersection[#,
  1368.                            Take[p, Position[p,x][[1,1]] ] ] ])&,
  1369.                     Reverse[ Drop[c,-1] ]
  1370.                 ]
  1371.             ],
  1372.             xlast
  1373.         ]
  1374.     ]
  1375.  
  1376. LongestIncreasingSubsequence[{}] := {}
  1377.  
  1378. AddToEncroachingLists[k_Integer,{}] := {{k}}
  1379.  
  1380. AddToEncroachingLists[k_Integer,l_List] :=
  1381.     Append[l,{k}]  /; (k > First[Last[l]]) && (k < Last[Last[l]])
  1382.  
  1383. AddToEncroachingLists[k_Integer,l1_List] :=
  1384.     Module[{i,l=l1},
  1385.         If [k <= First[Last[l]],
  1386.             i = Ceiling[ BinarySearch[l,k,First] ];
  1387.             PrependTo[l[[i]],k],
  1388.             i = Ceiling[ BinarySearch[l,-k,(-Last[#])&] ];
  1389.             AppendTo[l[[i]],k]
  1390.         ];
  1391.         l
  1392.     ]
  1393.  
  1394. EncroachingListSet[l_List] := EncroachingListSet[l,{}]
  1395. EncroachingListSet[{},e_List] := e
  1396.  
  1397. EncroachingListSet[l_List,e_List] :=
  1398.     EncroachingListSet[Rest[l], AddToEncroachingLists[First[l],e] ]
  1399.  
  1400. Edges[Graph[e_,_]] := e
  1401.  
  1402. Vertices[Graph[_,v_]] := v
  1403.  
  1404. V[Graph[e_,_]] := Length[e]
  1405.  
  1406. M[Graph[g_,_],___] := Apply[Plus, Map[(Apply[Plus,#])&,g] ] / 2
  1407. M[Graph[g_,_],Directed] := Apply[Plus, Map[(Apply[Plus,#])&,g] ]
  1408.  
  1409. ChangeVertices[g_Graph,v_List] := Graph[ Edges[g], v ]
  1410.  
  1411. ChangeEdges[g_Graph,e_List] := Graph[ e, Vertices[g] ]
  1412.  
  1413. AddEdge[Graph[g_,v_],{x_,y_},Directed] :=
  1414.     Module[ {gnew=g},
  1415.         gnew[[x,y]] ++;
  1416.         Graph[gnew,v]
  1417.     ]
  1418.  
  1419. AddEdge[g_Graph,{x_,y_},flag_:Undirected] :=
  1420.     AddEdge[ AddEdge[g, {x,y}, Directed], {y,x}, Directed]
  1421.  
  1422. DeleteEdge[Graph[g_,v_],{x_,y_},Directed] :=
  1423.     Module[ {gnew=g},
  1424.         If [ g[[x,y]] > 1, gnew[[x,y]]--, gnew[[x,y]] = 0];
  1425.         Graph[gnew,v]
  1426.     ]
  1427.  
  1428. DeleteEdge[g_Graph,{x_,y_},flag_:Undirected] :=
  1429.     DeleteEdge[ DeleteEdge[g, {x,y}, Directed], {y,x}, Directed]
  1430.  
  1431. AddVertex[g_Graph] := GraphUnion[g, K[1]]
  1432.  
  1433. DeleteVertex[g_Graph,v_Integer] := InduceSubgraph[g,Complement[Range[V[g]],{v}]]
  1434.  
  1435. Spectrum[Graph[g_,_]] := Eigenvalues[g]
  1436.  
  1437. ToAdjacencyLists[Graph[g_,_]] :=
  1438.     Map[ (Flatten[ Position[ #, _?(Function[n, n!=0])] ])&, g ]
  1439.  
  1440. FromAdjacencyLists[e_List] :=
  1441.     Module[{blanks = Table[0,{Length[e]}] },
  1442.         Graph[
  1443.             Map [ (MapAt[ 1&,blanks,Partition[#,1]])&, e ],
  1444.             CircularVertices[Length[e]]
  1445.         ]
  1446.     ]
  1447.  
  1448. FromAdjacencyLists[e_List,v_List] := ChangeVertices[FromAdjacencyLists[e], v]
  1449.  
  1450. ToOrderedPairs[g_Graph] := Position[ Edges[g], _?(Function[n,n != 0]) ]
  1451.  
  1452. ToUnorderedPairs[g_Graph] := Select[ ToOrderedPairs[g], (#[[1]] < #[[2]])& ]
  1453.  
  1454. FromOrderedPairs[l_List] := 
  1455.     Module[{n=Max[l]},
  1456.         Graph[
  1457.             MapAt[1&, Table[0,{n},{n}],l],
  1458.             CircularVertices[n]
  1459.         ]
  1460.     ]
  1461. FromOrderedPairs[{}] := Graph[{},{}]
  1462. FromOrderedPairs[l_List,v_List] := 
  1463.     Graph[ MapAt[1&, Table[0,{Length[v]},{Length[v]}], l], v]
  1464.  
  1465. FromUnorderedPairs[l_List] := MakeUndirected[ FromOrderedPairs[l] ]
  1466. FromUnorderedPairs[l_List,v_List] := MakeUndirected[ FromOrderedPairs[l,v] ]
  1467.  
  1468. PseudographQ[Graph[g_,_]] :=
  1469.     Module[{i},
  1470.         Apply[Or, Table[ g[[i,i]]!=0, {i,Length[g]} ]]
  1471.     ]
  1472.  
  1473. UnweightedQ[Graph[g_,_]] := Apply[ And, Map[(#==0 || #==1)&, Flatten[g] ] ]
  1474.  
  1475. SimpleQ[g_Graph] := (!PseudographQ[g]) && (UnweightedQ[g])
  1476.  
  1477. RemoveSelfLoops[g_Graph] :=
  1478.     Module[{i,e=Edges[g]},
  1479.         Do [ e[[i,i]]=0, {i,V[g]} ];
  1480.         Graph[e, Vertices[g]]
  1481.     ]    
  1482.  
  1483. EmptyQ[g_Graph] := Edges[g] == Table[0, {V[g]}, {V[g]}]
  1484.  
  1485. CompleteQ[g_Graph] := Edges[RemoveSelfLoops[g]] == Edges[ K[V[g]] ]
  1486.  
  1487. InduceSubgraph[g_Graph,{}] := Graph[{},{}]
  1488.  
  1489. InduceSubgraph[Graph[g_,v_],s_List] :=
  1490.     Graph[Transpose[Transpose[g[[s]]] [[s]] ],v[[s]]] /; (Length[s]<=Length[g])
  1491.  
  1492. Contract[g_Graph,{u_Integer,v_Integer}] :=
  1493.     Module[{o,e,i,n=V[g],newg,range=Complement[Range[V[g]],{u,v}]},
  1494.         newg = InduceSubgraph[g,range];
  1495.         e = Edges[newg]; o = Edges[g];
  1496.         Graph[
  1497.             Append[
  1498.                 Table[
  1499.                     Append[e[[i]],
  1500.                         If[o[[range[[i]],u]]>0 ||
  1501.                             o[[range[[i]],v]]>0,1,0] ],
  1502.                     {i,n-2}
  1503.                 ],
  1504.                 Append[
  1505.                     Map[(If[o[[u,#]]>0||o[[v,#]]>0,1,0])&,range],
  1506.                     0
  1507.                 ]
  1508.             ],
  1509.             Join[Vertices[newg], {(Vertices[g][[u]]+Vertices[g][[v]])/2}]
  1510.         ]
  1511.     ] /; V[g] > 2
  1512.  
  1513. Contract[g_Graph,_] := K[1]    /; V[g] == 2
  1514.  
  1515. GraphComplement[Graph[g_,v_]] :=
  1516.     RemoveSelfLoops[ Graph[ Map[ (Map[ (If [#==0,1,0])&, #])&, g], v ] ]
  1517.  
  1518. MakeUndirected[Graph[g_,v_]] :=
  1519.     Module[{i,j,n=Length[g]},
  1520.         Graph[ Table[If [g[[i,j]]!=0 || g[[j,i]]!=0,1,0],{i,n},{j,n}], v ]
  1521.     ]
  1522.  
  1523. UndirectedQ[Graph[g_,_]] := (Apply[Plus,Apply[Plus,Abs[g-Transpose[g]]]] == 0)
  1524.  
  1525. MakeSimple[g_Graph] := MakeUndirected[RemoveSelfLoops[g]]
  1526.  
  1527. BFS[g_Graph,start_Integer] :=
  1528.     Module[{e,bfi=Table[0,{V[g]}],cnt=1,edges={},queue={start}},
  1529.         e = ToAdjacencyLists[g];
  1530.         bfi[[start]] = cnt++;
  1531.         While[ queue != {},
  1532.             {v,queue} = {First[queue],Rest[queue]};
  1533.             Scan[
  1534.                 (If[ bfi[[#]] == 0,
  1535.                     bfi[[#]] = cnt++;
  1536.                     AppendTo[edges,{v,#}];
  1537.                     AppendTo[queue,#]
  1538.                 ])&,
  1539.                 e[[v]]
  1540.             ];
  1541.         ];
  1542.         {edges,bfi}
  1543.     ]
  1544.                 
  1545. BreadthFirstTraversal[g_Graph,s_Integer,Edge] := First[BFS[g,s]]
  1546.  
  1547. BreadthFirstTraversal[g_Graph,s_Integer,___] := InversePermutation[Last[BFS[g,s]]]
  1548.  
  1549. DFS[v_Integer] :=
  1550.     ( dfi[[v]] = cnt++;
  1551.       AppendTo[visit,v];
  1552.       Scan[ (If[dfi[[#]]==0,AppendTo[edges,{v,#}];DFS[#] ])&, e[[v]] ] )
  1553.  
  1554. DepthFirstTraversal[g_Graph,start_Integer,flag_:Vertex] :=
  1555.     Block[{visit={},e=ToAdjacencyLists[g],edges={},dfi=Table[0,{V[g]}],cnt=1},
  1556.         DFS[start];
  1557.         If[ flag===Edge, edges, visit]
  1558.     ]
  1559.  
  1560. ShowGraph[g1_Graph,type_:Undirected] :=
  1561.     Module[{g=NormalizeVertices[g1]},
  1562.         Show[
  1563.             Graphics[
  1564.                 Join[
  1565.                     PointsAndLines[g],
  1566.                     If[SameQ[type,Directed],Arrows[g],{}]
  1567.                 ]
  1568.             ], 
  1569.             {AspectRatio->1, PlotRange->FindPlotRange[Vertices[g]]}
  1570.         ]
  1571.     ]
  1572.  
  1573. MinimumEdgeLength[v_List,pairs_List] :=
  1574.     Max[ Select[
  1575.         Chop[ Map[(Sqrt[ N[(v[[#[[1]]]]-v[[#[[2]]]]) . 
  1576.             (v[[#[[1]]]]-v[[#[[2]]]])] ])&,pairs] ],
  1577.         (# > 0)&
  1578.     ], 0.001 ]
  1579.  
  1580. FindPlotRange[v_List] :=
  1581.     Module[{xmin=Min[Map[First,v]], xmax=Max[Map[First,v]],
  1582.             ymin=Min[Map[Last,v]], ymax=Max[Map[Last,v]]},
  1583.         { {xmin - 0.05 Max[1,xmax-xmin], xmax + 0.05 Max[1,xmax-xmin]},
  1584.           {ymin - 0.05 Max[1,ymax-ymin], ymax + 0.05 Max[1,ymax-ymin]} }
  1585.     ]
  1586.  
  1587. PointsAndLines[Graph[e_List,v_List]] :=
  1588.     Module[{pairs=ToOrderedPairs[Graph[e,v]]},
  1589.         Join[
  1590.             {PointSize[ 0.025 ]},
  1591.             Map[Point,Chop[v]],
  1592.             Map[(Line[Chop[ v[[#]] ]])&,pairs]
  1593.         ]
  1594.     ]
  1595.  
  1596. Arrows[Graph[e_,v_]] :=
  1597.     Module[{pairs=ToOrderedPairs[Graph[e,v]], size, triangle},
  1598.         size = Min[0.05, MinimumEdgeLength[v,pairs]/3];
  1599.         triangle={ {0,0}, {-size,size/2}, {-size,-size/2} };
  1600.         Map[
  1601.             (Polygon[
  1602.                 TranslateVertices[
  1603.                     RotateVertices[
  1604.                         triangle,
  1605.                         Arctan[Apply[Subtract,v[[#]]]]+Pi
  1606.                     ],
  1607.                     v[[ #[[2]] ]]
  1608.                 ]
  1609.             ])&,
  1610.             pairs
  1611.         ]
  1612.     ]
  1613.  
  1614. ShowLabeledGraph[g_Graph] := ShowLabeledGraph[g,Range[V[g]]]
  1615. ShowLabeledGraph[g1_Graph,labels_List] :=
  1616.     Module[{pairs=ToOrderedPairs[g1], g=NormalizeVertices[g1], v},
  1617.         v = Vertices[g];
  1618.         Show[
  1619.             Graphics[
  1620.                 Join[
  1621.                     PointsAndLines[g],
  1622.                     Map[(Line[Chop[ v[[#]] ]])&, pairs],
  1623.                     GraphLabels[v,labels]
  1624.                 ]
  1625.             ],
  1626.             {AspectRatio->1, PlotRange->FindPlotRange[v]} 
  1627.         ]
  1628.     ]
  1629.  
  1630. GraphLabels[v_List,l_List] :=
  1631.     Module[{i},
  1632.         Table[ Text[ l[[i]],v[[i]]-{0.03,0.03},{0,1} ],{i,Length[v]}]
  1633.     ]
  1634.  
  1635. CircularVertices[0] := {}
  1636.  
  1637. CircularVertices[n_Integer] :=
  1638.     Module[{i,x = N[2 Pi / n]},
  1639.         Chop[ Table[ N[{ (Cos[x i]), (Sin[x i]) }], {i,n} ] ]
  1640.     ]
  1641.  
  1642. CircularVertices[Graph[g_,_]] := Graph[ g, CircularVertices[ Length[g] ] ]
  1643.  
  1644. RankGraph[g_Graph, start_List] :=
  1645.     Module[ {rank = Table[0,{V[g]}],edges = ToAdjacencyLists[g],v,queue,new},
  1646.         Scan[ (rank[[#]] = 1)&, start];
  1647.         queue = start;
  1648.         While [queue != {},
  1649.             v = First[queue];
  1650.             new = Select[ edges[[v]], (rank[[#]] == 0)&];
  1651.             Scan[ (rank[[#]] = rank[[v]]+1)&, new];
  1652.             queue = Join[ Rest[queue], new];
  1653.         ];
  1654.         rank
  1655.     ]
  1656.  
  1657. RankedEmbedding[g_Graph,start_List] := Graph[ Edges[g],RankedVertices[g,start] ]
  1658.  
  1659. RankedVertices[g_Graph,start_List] :=
  1660.     Module[{i,m,stages,rank,freq = Table[0,{V[g]}]},
  1661.         rank = RankGraph[g,start];
  1662.         stages = Distribution[ rank ];
  1663.         Table[
  1664.             m = ++ freq[[ rank[[i]] ]];
  1665.             {rank[[i]], (m-1) + (1 - stages[[ rank[[i]] ]])/2 },
  1666.             {i,V[g]}
  1667.         ]
  1668.     ]
  1669.  
  1670. Distribution[l_List] := Distribution[l, Union[l]]
  1671. Distribution[l_List, set_List] := Map[(Count[l,#])&, set]
  1672.  
  1673. Eccentricity[g_Graph] := Map[ Max, AllPairsShortestPath[g] ]
  1674. Eccentricity[g_Graph,start_Integer] := Map[ Max, Last[Dijkstra[g,start]] ]
  1675.  
  1676. Diameter[g_Graph] := Max[ Eccentricity[g] ]
  1677.  
  1678. Radius[g_Graph] := Min[ Eccentricity[g] ]
  1679.  
  1680. GraphCenter[g_Graph] := 
  1681.     Module[{eccentricity = Eccentricity[g]},
  1682.         Flatten[ Position[eccentricity, Min[eccentricity]] ]
  1683.     ]
  1684.  
  1685. RadialEmbedding[g_Graph,ct_Integer] :=
  1686.     Module[{center=ct,ang,i,da,theta,n,v,positioned,done,next,e=ToAdjacencyLists[g]},
  1687.         ang = Table[{0,2 Pi},{n=V[g]}];
  1688.         v = Table[{0,0},{n}];
  1689.         positioned = next = done = {center};
  1690.         While [next != {},
  1691.             center = First[next];
  1692.             new = Complement[e[[center]], positioned];
  1693.             Do [
  1694.                 da = (ang[[center,2]]-ang[[center,1]])/Length[new];
  1695.                 ang[[ new[[i]] ]] = {ang[[center,1]] + (i-1)*da,
  1696.                     ang[[center,1]] + i*da};
  1697.                 theta = Apply[Plus,ang[[ new[[i]] ]] ]/2;
  1698.                 v[[ new[[i]] ]] = v[[center]] +
  1699.                     N[{Cos[theta],Sin[theta]}],
  1700.                 {i,Length[new]}
  1701.             ];
  1702.             next = Join[Rest[next],new];
  1703.             positioned = Union[positioned,new];
  1704.             AppendTo[done,center]
  1705.         ];
  1706.         Graph[Edges[g],v]
  1707.     ]
  1708.  
  1709. RadialEmbedding[g_Graph] := RadialEmbedding[g,First[GraphCenter[g]]];
  1710.  
  1711. RootedEmbedding[g_Graph,rt_Integer] :=
  1712.     Module[{root=rt,pos,i,x,dx,new,n=V[g],v,done,next,e=ToAdjacencyLists[g]},
  1713.         pos = Table[{-Ceiling[Sqrt[n]],Ceiling[Sqrt[n]]},{n}];
  1714.         v = Table[{0,0},{n}];
  1715.         next = done = {root};
  1716.         While [next != {},
  1717.             root = First[next];
  1718.             new = Complement[e[[root]], done];
  1719.             Do [
  1720.                 dx = (pos[[root,2]]-pos[[root,1]])/Length[new];
  1721.                 pos[[ new[[i]] ]] = {pos[[root,1]] + (i-1)*dx,
  1722.                     pos[[root,1]] + i*dx};
  1723.                 x = Apply[Plus,pos[[ new[[i]] ]] ]/2;
  1724.                 v[[ new[[i]] ]] = {x,v[[root,2]]-1},
  1725.                 {i,Length[new]}
  1726.             ];
  1727.             next = Join[Rest[next],new];
  1728.             done = Join[done,new]
  1729.         ];
  1730.         Graph[Edges[g],N[v]]
  1731.     ]
  1732.  
  1733. TranslateVertices[v_List,{x_,y_}] := Map[ (# + {x,y})&, v ]
  1734. TranslateVertices[Graph[g_,v_],{x_,y_}] := Graph[g, TranslateVertices[v,{x,y}] ]
  1735.  
  1736. DilateVertices[v_List,d_] := (d * v)
  1737. DilateVertices[Graph[e_,v_],d_] := Graph[e, DilateVertices[v,d]]
  1738.  
  1739. RotateVertices[v_List,t_] := 
  1740.     Module[{d,theta},
  1741.         Map[
  1742.             (If[# == {0,0}, {0,0},
  1743.                 d=Sqrt[#[[1]]^2 + #[[2]]^2];
  1744.                  theta = t + Arctan[#];
  1745.                  N[{d Cos[theta], d Sin[theta]}]
  1746.             ])&,
  1747.             v
  1748.         ]
  1749.     ]
  1750. RotateVertices[Graph[g_,v_],t_] := Graph[g, RotateVertices[v,t]]
  1751.  
  1752. Arctan[{x_,y_}] := Arctan1[Chop[{x,y}]]
  1753. Arctan1[{0,0}] := 0
  1754. Arctan1[{x_,y_}] := ArcTan[x,y]
  1755.  
  1756. NormalizeVertices[v_List] := 
  1757.     Module[{v1},
  1758.         v1 = TranslateVertices[v,{-Min[v],-Min[v]}];
  1759.         DilateVertices[v1, 1/Max[v1,0.01]]
  1760.     ]
  1761.  
  1762. NormalizeVertices[Graph[g_,v_]] := Graph[g, NormalizeVertices[v]]
  1763.  
  1764. ShakeGraph[Graph[e_List,v_List], fract_:0.1] :=
  1765.     Module[{i,d,a},
  1766.         Graph[
  1767.             e,
  1768.             Table[ 
  1769.                 d = Random[Real,{0,fract}];
  1770.                 a = Random[Real,{0, 2 N[Pi]}];
  1771.                 {N[v[[i,1]] + d Cos[a]], N[v[[i,2]] + d Sin[a]]},
  1772.                 {i,Length[e]}
  1773.             ]
  1774.         ]
  1775.     ]
  1776.  
  1777. CalculateForce[u_Integer,g_Graph,em_List] :=
  1778.     Module[{n=V[g],stc=0.25,gr=10.0,e=Edges[g],f={0.0,0.0},spl=1.0,v,dsquared},
  1779.         Do [
  1780.             dsquared = Max[0.001, Apply[Plus,(em[[u]]-em[[v]])^2] ];
  1781.             f += (1-e[[u,v]]) (gr/dsquared) (em[[u]]-em[[v]])
  1782.                 - e[[u,v]] stc Log[dsquared/spl] (em[[u]]-em[[v]]),
  1783.             {v,n}
  1784.         ];
  1785.         f
  1786.     ]
  1787.  
  1788. SpringEmbedding[g_Graph,step_:10,inc_:0.15] :=
  1789.     Module[{new=old=Vertices[g],n=V[g],i,u,g1=MakeUndirected[g]},
  1790.         Do [
  1791.             Do [
  1792.                 new[[u]] = old[[u]]+inc*CalculateForce[u,g1,old],
  1793.                 {u,n}
  1794.             ];
  1795.             old = new,
  1796.             {i,step}
  1797.         ];
  1798.         Graph[Edges[g],new]
  1799.     ]
  1800.  
  1801. (*    Rewritten for Version 2.0    *)
  1802.  
  1803. ReadGraph[file_] :=
  1804.     Module[{edgelist={}, v={},x},
  1805.         OpenRead[file];
  1806.         While[!SameQ[(x = Read[file,Number]), EndOfFile],
  1807.             AppendTo[v,Read[file,{Number,Number}]];
  1808.             AppendTo[edgelist,
  1809.                 Convert[Characters[Read[file,String]]]
  1810.             ];
  1811.         ];
  1812.         Close[file];
  1813.         FromAdjacencyLists[edgelist,v]
  1814.     ]
  1815.  
  1816. Toascii[s_String] := First[ ToCharacterCode[s] ]
  1817.  
  1818. Convert[l_List] := 
  1819.     Module[{ch,num,edge={},i=1},
  1820.         While[i <= Length[l],
  1821.             If[ DigitQ[ l[[i]] ], 
  1822.                 num = 0;
  1823.                 While[ ((i <= Length[l]) && (DigitQ[l[[i]]])),
  1824.                     num = 10 num + Toascii[l[[i++]]] - Toascii["0"]
  1825.                 ];
  1826.                 AppendTo[edge,num],
  1827.                 i++
  1828.             ];
  1829.         ];
  1830.         edge
  1831.     ]
  1832.  
  1833. WriteGraph[g_Graph,file_] := 
  1834.     Module[{edges=ToAdjacencyLists[g],v=N[NormalizeVertices[Vertices[g]]],i,x,y},
  1835.         OpenWrite[file];
  1836.         Do[
  1837.             WriteString[file,"    ",ToString[i]];
  1838.             {x,y} = Chop[ v [[i]] ];
  1839.             WriteString[file,"    ",ToString[x],"    ",ToString[y]];
  1840.             Scan[
  1841.                 (WriteString[file,"    ",ToString[ # ]])&,
  1842.                 edges[[i]]
  1843.             ];
  1844.             Write[file],
  1845.             {i,V[g]}
  1846.         ];
  1847.         Close[file];
  1848.     ]
  1849.  
  1850. GraphUnion[g_Graph,h_Graph] :=
  1851.     Module[{maxg=Max[ Map[First,Vertices[g]] ], minh=Min[ Map[First,Vertices[h]] ]},
  1852.         FromOrderedPairs[
  1853.             Join[ ToOrderedPairs[g], (ToOrderedPairs[h] + V[g])],
  1854.             Join[ Vertices[g], Map[({maxg-minh+1,0}+#)&, Vertices[h] ] ]
  1855.         ]
  1856.     ]
  1857.  
  1858. GraphUnion[1,g_Graph] := g
  1859. GraphUnion[0,g_Graph] := EmptyGraph[0];
  1860. GraphUnion[k_Integer,g_Graph] := GraphUnion[ GraphUnion[k-1,g], g]
  1861.  
  1862. ExpandGraph[g_Graph,n_] := GraphUnion[ g, EmptyGraph[n - V[g]] ] /; V[g] <= n
  1863.  
  1864. GraphIntersection[g_Graph,h_Graph] :=
  1865.     FromOrderedPairs[
  1866.         Intersection[ToOrderedPairs[g],ToOrderedPairs[h]],
  1867.         Vertices[g]
  1868.     ] /; (V[g] == V[h])
  1869.  
  1870. GraphDifference[g1_Graph,g2_Graph] :=
  1871.     Graph[Edges[g1] - Edges[g2], Vertices[g1]] /; V[g1]==V[g2]
  1872.  
  1873. GraphSum[g1_Graph,g2_Graph] :=
  1874.     Graph[Edges[g1] + Edges[g2], Vertices[g1]] /; V[g1]==V[g2]
  1875.  
  1876. GraphJoin[g_Graph,h_Graph] :=
  1877.     Module[{maxg=Max[ Abs[ Map[First,Vertices[g]] ] ]},
  1878.         FromUnorderedPairs[
  1879.             Join[
  1880.                 ToUnorderedPairs[g],
  1881.                 ToUnorderedPairs[h] + V[g],
  1882.                 CartesianProduct[Range[V[g]],Range[V[h]]+V[g]]
  1883.             ],
  1884.             Join[ Vertices[g], Map[({maxg+1,0}+#)&, Vertices[h]]]
  1885.         ]
  1886.     ]
  1887.  
  1888. CartesianProduct[a_List,b_List] :=
  1889.     Module[{i,j},
  1890.         Flatten[ Table[{a[[i]],b[[j]]},{i,Length[a]},{j,Length[b]}], 1]
  1891.     ]
  1892.  
  1893. GraphProduct[g_Graph,h_Graph] :=
  1894.     Module[{k,eg=ToOrderedPairs[g],eh=ToOrderedPairs[h],leng=V[g],lenh=V[h]},
  1895.         FromOrderedPairs[
  1896.             Flatten[
  1897.                 Join[
  1898.                     Table[eg+(i-1)*leng, {i,lenh}],
  1899.                     Map[ (Table[
  1900.                         {leng*(#[[1]]-1)+k, leng*(#[[2]]-1)+k},
  1901.                         {k,1,leng}
  1902.                           ])&,
  1903.                           eh
  1904.                     ]
  1905.                 ],
  1906.                 1
  1907.             ],
  1908.             ProductVertices[Vertices[g],Vertices[h]]
  1909.         ]
  1910.     ]
  1911.  
  1912. ProductVertices[vg_,vh_] :=
  1913.     Flatten[
  1914.         Map[
  1915.             (TranslateVertices[
  1916.                 DilateVertices[vg, 1/(Max[Length[vg],Length[vh]])],
  1917.             #])&,
  1918.              RotateVertices[vh,Pi/2]
  1919.         ],
  1920.         1
  1921.     ]
  1922.  
  1923. IncidenceMatrix[g_Graph] :=
  1924.     Map[
  1925.         ( Join[
  1926.             Table[0,{First[#]-1}], {1},
  1927.             Table[0,{Last[#]-First[#]-1}], {1},
  1928.             Table[0,{V[g]-Last[#]}]
  1929.         ] )&,
  1930.         ToUnorderedPairs[g]
  1931.     ]
  1932.  
  1933. LineGraph[g_Graph] :=
  1934.     Module[{b=IncidenceMatrix[g], edges=ToUnorderedPairs[g], v=Vertices[g]},
  1935.         Graph[
  1936.             b . Transpose[b] - 2 IdentityMatrix[Length[edges]],
  1937.             Map[ ( (v[[ #[[1]] ]] + v[[ #[[2]] ]]) / 2 )&, edges]
  1938.         ]
  1939.     ]
  1940.  
  1941. K[0] := Graph[{},{}]
  1942. K[1] := Graph[{{0}},{{0,0}}]
  1943.  
  1944. K[n_Integer?Positive] := CirculantGraph[n,Range[1,Floor[(n+1)/2]]]
  1945.  
  1946. CirculantGraph[n_Integer?Positive,l_List] :=
  1947.     Module[{i,r},
  1948.         r = Prepend[MapAt[1&,Table[0,{n-1}], Map[List,Join[l,n-l]]], 0];
  1949.         Graph[ Table[RotateRight[r,i], {i,0,n-1}], CircularVertices[n] ]
  1950.     ]
  1951.  
  1952. EmptyGraph[n_Integer?Positive] :=
  1953.     Module[{i},
  1954.         Graph[ Table[0,{n},{n}], Table[{0,i},{i,(1-n)/2,(n-1)/2}] ]
  1955.     ]
  1956.  
  1957. K[l__] :=
  1958.     Module[{ll=List[l],t,i,x,row,stages=Length[List[l]]},
  1959.         t = FoldList[Plus,0,ll];
  1960.         Graph[
  1961.             Apply[
  1962.                 Join,
  1963.                 Table [
  1964.                     row = Join[
  1965.                         Table[1, {t[[i-1]]}],
  1966.                         Table[0, {t[[i]]-t[[i-1]]}],
  1967.                         Table[1, {t[[stages+1]]-t[[i]]}]
  1968.                     ];
  1969.                     Table[row, {ll[[i-1]]}],
  1970.                     {i,2,stages+1}
  1971.                 ]
  1972.             
  1973.             ],
  1974.             Apply [
  1975.                 Join,
  1976.                 Table[
  1977.                     Table[{x,i-1+(1-ll[[x]])/2},{i,ll[[x]]}],
  1978.                     {x,stages}
  1979.                 ]
  1980.             ]
  1981.         ]
  1982.     ] /; TrueQ[Apply[And, Map[Positive,List[l]]]] && (Length[List[l]]>1)
  1983.  
  1984. Turan[n_Integer,p_Integer] :=
  1985.     Module[{k = Floor[ n / (p-1) ], r},
  1986.         r = n - k (p-1);
  1987.         Apply[K, Join[ Table[k,{p-1-r}], Table[k+1,{r}] ] ]
  1988.     ] /; (n > 0 && p > 1)
  1989.  
  1990. Cycle[n_Integer] := CirculantGraph[n,{1}]  /; n>=3
  1991.  
  1992. Star[n_Integer?Positive] :=
  1993.     Module[{g},
  1994.         g = Append [ Table[0,{n-1},{n}], Append[ Table[1,{n-1}], 0] ];
  1995.         Graph[
  1996.             g + Transpose[g],
  1997.             Append[ CircularVertices[n-1], {0,0}]
  1998.         ]
  1999.     ]
  2000.  
  2001. Wheel[n_Integer] :=
  2002.     Module[{i,row = Join[{0,1}, Table[0,{n-4}], {1}]},
  2003.         Graph[
  2004.             Append[
  2005.                 Table[ Append[RotateRight[row,i-1],1], {i,n-1}],
  2006.                 Append[ Table[1,{n-1}], 0]
  2007.             ],
  2008.             Append[ CircularVertices[n-1], {0,0} ]
  2009.         ]
  2010.     ] /; n >= 3
  2011.  
  2012. Path[1] := K[1]
  2013. Path[n_Integer?Positive] :=
  2014.     FromUnorderedPairs[ Partition[Range[n],2,1], Map[({#,0})&,Range[n]] ]
  2015.  
  2016. GridGraph[n_Integer?Positive,m_Integer?Positive] :=
  2017.     GraphProduct[
  2018.         ChangeVertices[Path[n], Map[({Max[n,m]*#,0})&,Range[n]]],
  2019.         Path[m]
  2020.     ]
  2021.  
  2022. Hypercube[n_Integer] := Hypercube1[n]
  2023.  
  2024. Hypercube1[0] := K[1]
  2025. Hypercube1[1] := Path[2]
  2026. Hypercube1[2] := Cycle[4]
  2027.  
  2028. Hypercube1[n_Integer] := Hypercube1[n] =
  2029.     GraphProduct[
  2030.         RotateVertices[ Hypercube1[Floor[n/2]], 2Pi/5],
  2031.         Hypercube1[Ceiling[n/2]]
  2032.     ]
  2033.  
  2034. LabeledTreeToCode[g_Graph] :=
  2035.     Module[{e=ToAdjacencyLists[g],i,code},
  2036.         Table [
  2037.             {i} = First[ Position[ Map[Length,e], 1 ] ];
  2038.             code = e[[i,1]];
  2039.             e[[code]] = Complement[ e[[code]], {i} ];
  2040.             e[[i]] = {};
  2041.             code,
  2042.             {V[g]-2}
  2043.         ]
  2044.     ]
  2045.  
  2046. CodeToLabeledTree[l_List] :=
  2047.     Module[{m=Range[Length[l]+2],x,i},
  2048.         FromUnorderedPairs[
  2049.             Append[
  2050.                 Table[
  2051.                     x = Min[Complement[m,Drop[l,i-1]]];
  2052.                     m = Complement[m,{x}];
  2053.                     {x,l[[i]]},
  2054.                     {i,Length[l]}
  2055.                 ],
  2056.                 m
  2057.             ]
  2058.         ]
  2059.     ]
  2060.  
  2061. RandomTree[n_Integer?Positive] :=
  2062.     RadialEmbedding[CodeToLabeledTree[ Table[Random[Integer,{1,n}],{n-2}] ], 1]
  2063.  
  2064. RandomGraph[n_Integer,p_] := RandomGraph[n,p,{1,1}]
  2065.  
  2066. RandomGraph[n_Integer,p_,range_List] :=
  2067.     Module[{i,g},
  2068.         g = Table[ 
  2069.             Join[
  2070.                 Table[0,{i}],
  2071.                 Table[ 
  2072.                     If[Random[Real]<p, Random[Integer,range], 0],
  2073.                     {n-i}
  2074.                 ]
  2075.             ],
  2076.             {i,n}
  2077.         ];
  2078.         Graph[ g + Transpose[g], CircularVertices[n] ]
  2079.     ]
  2080.  
  2081. ExactRandomGraph[n_Integer,e_Integer] :=
  2082.     FromUnorderedPairs[
  2083.         Map[ NthPair, Take[ RandomPermutation[n(n-1)/2], e] ],
  2084.         CircularVertices[n]
  2085.     ]
  2086.  
  2087. NthPair[0] := {}
  2088. NthPair[n_Integer] :=
  2089.     Module[{i=2},
  2090.         While[ Binomial[i,2] < n, i++];
  2091.         {n - Binomial[i-1,2], i}
  2092.     ]
  2093.  
  2094. RandomVertices[n_Integer] := Table[{Random[], Random[]}, {n}]
  2095. RandomVertices[g_Graph] := Graph[ Edges[g], RandomVertices[V[g]] ]
  2096.  
  2097. RandomGraph[n_Integer,p_,range_List,Directed] :=
  2098.     RemoveSelfLoops[
  2099.         Graph[
  2100.             Table[If[Random[Real]<p,Random[Integer,range],0],{n},{n}],
  2101.             CircularVertices[n]
  2102.         ]
  2103.     ]
  2104.  
  2105. RandomGraph[n_Integer,p_,Directed] := RandomGraph[n,p,{1,1},Directed]
  2106.  
  2107. DegreeSequence[g_Graph] := Reverse[ Sort[ Degrees[g] ] ]
  2108.  
  2109. Degrees[Graph[g_,_]] := Map[(Apply[Plus,#])&, g]
  2110.  
  2111. GraphicQ[s_List] := False /; (Min[s] < 0) || (Max[s] >= Length[s])
  2112. GraphicQ[s_List] := (First[s] == 0) /; (Length[s] == 1)
  2113. GraphicQ[s_List] :=
  2114.     Module[{m,sorted = Reverse[Sort[s]]},
  2115.         m = First[sorted];
  2116.         GraphicQ[ Join[ Take[sorted,{2,m+1}]-1, Drop[sorted,m+1] ] ]
  2117.     ]
  2118.  
  2119. RealizeDegreeSequence[d_List] :=
  2120.     Module[{i,j,v,set,seq,n=Length[d],e},
  2121.         seq = Reverse[ Sort[ Table[{d[[i]],i},{i,n}]] ];
  2122.         FromUnorderedPairs[
  2123.             Flatten[ Table[
  2124.                 {{k,v},seq} = {First[seq],Rest[seq]};
  2125.                 While[ !GraphicQ[
  2126.                     MapAt[
  2127.                         (# - 1)&,
  2128.                         Map[First,seq],
  2129.                         set = RandomKSubset[Table[{i},{i,n-j}],k] 
  2130.                     ] ],
  2131.                 ];
  2132.                 e = Map[(Prepend[seq[[#,2]],v])&,set];
  2133.                 seq = Reverse[ Sort[
  2134.                     MapAt[({#[[1]]-1,#[[2]]})&,seq,set]
  2135.                 ] ];
  2136.                 e,
  2137.                 {j,Length[d]-1}
  2138.             ], 1],
  2139.             CircularVertices[n]
  2140.         ]
  2141.     ] /; GraphicQ[d]
  2142.  
  2143. RealizeDegreeSequence[d_List,seed_Integer] :=
  2144.     (SeedRandom[seed]; RealizeDegreeSequence[d])
  2145.  
  2146. RegularQ[Graph[g_,_]] := Apply[ Equal, Map[(Apply[Plus,#])& , g] ]
  2147.  
  2148. RegularGraph[k_Integer,n_Integer] := RealizeDegreeSequence[Table[k,{n}]]
  2149.  
  2150. MakeGraph[v_List,f_] :=
  2151.     Module[{n=Length[v],i,j},
  2152.         Graph [
  2153.             Table[If [Apply[f,{v[[i]],v[[j]]}], 1, 0],{i,n},{j,n}],
  2154.             CircularVertices[n]
  2155.         ]
  2156.     ]
  2157.  
  2158. IntervalGraph[l_List] :=
  2159.     MakeGraph[
  2160.         l,
  2161.         ( ((First[#1] <= First[#2]) && (Last[#1] >= First[#2])) ||
  2162.           ((First[#2] <= First[#1]) && (Last[#2] >= First[#1])) )&
  2163.     ]
  2164.  
  2165. FunctionalGraph[f_,n_] :=
  2166.     Module[{i,x},
  2167.         FromOrderedPairs[
  2168.             Table[{i, x=Mod[Apply[f,{i}],n]; If[x!=0,x,n]}, {i,n} ],
  2169.             CircularVertices[n]
  2170.         ]
  2171.     ]
  2172.  
  2173. ConnectedComponents[g_Graph] :=
  2174.     Module[{untraversed=Range[V[g]],traversed,comps={}},
  2175.         While[untraversed != {},
  2176.             traversed = DepthFirstTraversal[g,First[untraversed]];
  2177.             AppendTo[comps,traversed];
  2178.             untraversed = Complement[untraversed,traversed]
  2179.         ];
  2180.         comps
  2181.     ]
  2182.  
  2183. ConnectedQ[g_Graph] := Length[ DepthFirstTraversal[g,1] ] == V[g]
  2184.  
  2185. WeaklyConnectedComponents[g_Graph] := ConnectedComponents[ MakeUndirected[g] ]
  2186.  
  2187. ConnectedQ[g_Graph,Undirected] := Length[ WeaklyConnectedComponents[g] ] == 1
  2188.  
  2189. StronglyConnectedComponents[g_Graph] :=
  2190.     Block[{e=ToAdjacencyLists[g],s,c=1,i,cur={},low=dfs=Table[0,{V[g]}],scc={}},
  2191.         While[(s=Select[Range[V[g]],(dfs[[#]]==0)&]) != {},
  2192.             SearchStrongComp[First[s]];
  2193.         ];
  2194.         scc
  2195.     ]
  2196.  
  2197. SearchStrongComp[v_Integer] :=
  2198.     Block[{r},
  2199.         low[[v]]=dfs[[v]]=c++;
  2200.         PrependTo[cur,v];
  2201.         Scan[
  2202.             (If[dfs[[#]] == 0,
  2203.                 SearchStrongComp[#];
  2204.                 low[[v]]=Min[low[[v]],low[[#]]],
  2205.                 If[(dfs[[#]] < dfs[[v]]) && MemberQ[cur,#],
  2206.                     low[[v]]=Min[low[[v]],dfs[[#]] ]
  2207.                 ];
  2208.             ])&,
  2209.             e[[v]]
  2210.         ];
  2211.         If[low[[v]] == dfs[[v]],
  2212.             {r} = Flatten[Position[cur,v]];
  2213.             AppendTo[scc,Take[cur,r]];
  2214.             cur = Drop[cur,r];
  2215.         ];
  2216.     ]
  2217.  
  2218. ConnectedQ[g_Graph,Directed] := Length[ StronglyConnectedComponents[g] ] == 1
  2219.  
  2220. OrientGraph[g_Graph] :=
  2221.     Module[{pairs,newg,rest,cc,c,i,e},
  2222.         pairs = Flatten[Map[(Partition[#,2,1])&,ExtractCycles[g]],1];
  2223.         newg = FromUnorderedPairs[pairs,Vertices[g]];
  2224.         rest = ToOrderedPairs[ GraphDifference[ g, newg ] ];
  2225.         cc = Sort[ConnectedComponents[newg], (Length[#1]>=Length[#2])&];
  2226.         c = First[cc];
  2227.         Do[
  2228.             e = Select[rest,(MemberQ[c,#[[1]]] &&
  2229.                      MemberQ[cc[[i]],#[[2]]])&];
  2230.             rest = Complement[rest,e,Map[Reverse,e]];
  2231.             c = Union[c,cc[[i]]];
  2232.             pairs = Join[pairs, Prepend[ Rest[e],Reverse[e[[1]]] ] ],
  2233.             {i,2,Length[cc]}
  2234.         ];
  2235.         FromOrderedPairs[
  2236.             Join[pairs, Select[rest,(#[[1]] > #[[2]])&] ],
  2237.             Vertices[g]
  2238.         ]
  2239.     ] /; SameQ[Bridges[g],{}]
  2240.  
  2241. FindBiconnectedComponents[g_Graph] :=
  2242.     Block[{e=ToAdjacencyLists[g],n=V[g],par,c=0,act={},back,dfs,ap=bcc={}},
  2243.         back=dfs=Table[0,{n}];
  2244.         par = Table[n+1,{n}]; 
  2245.         Map[(SearchBiConComp[First[#]])&, ConnectedComponents[g]];
  2246.         {bcc,Drop[ap, -1]}
  2247.     ]
  2248.  
  2249. SearchBiConComp[v_Integer] :=
  2250.     Block[{r},
  2251.         back[[v]]=dfs[[v]]=++c;
  2252.         Scan[
  2253.             (If[ dfs[[#]] == 0, 
  2254.                 If[!MemberQ[act,{v,#}], PrependTo[act,{v,#}]];
  2255.                 par[[#]] = v;
  2256.                 SearchBiConComp[#];
  2257.                 If[ back[[#]] >= dfs[[v]],
  2258.                     {r} = Flatten[Position[act,{v,#}]];
  2259.                     AppendTo[bcc,Union[Flatten[Take[act,r]]]];
  2260.                     AppendTo[ap,v];
  2261.                     act = Drop[act,r]
  2262.                 ];
  2263.                 back[[v]] = Min[ back[[v]],back[[#]] ],
  2264.                 If[# != par[[v]],back[[v]]=Min[dfs[[#]],back[[v]]]]
  2265.             ])&,
  2266.             e[[v]]
  2267.         ];
  2268.     ]
  2269.  
  2270. ArticulationVertices[g_Graph]  := Union[Last[FindBiconnectedComponents[g]]];
  2271.  
  2272. Bridges[g_Graph] := Select[BiconnectedComponents[g],(Length[#] == 2)&]
  2273.  
  2274. BiconnectedComponents[g_Graph] := First[FindBiconnectedComponents[g]];
  2275.  
  2276. BiconnectedQ[g_Graph] := Length[ BiconnectedComponents[g] ] == 1
  2277.  
  2278. EdgeConnectivity[g_Graph] :=
  2279.     Module[{i},
  2280.         Apply[Min, Table[NetworkFlow[g,1,i], {i,2,V[g]}]]
  2281.     ]
  2282.  
  2283. VertexConnectivityGraph[g_Graph] :=
  2284.     Module[{n=V[g],e},
  2285.         e=Table[0,{2 n},{2 n}];
  2286.         Scan[ (e[[#-1,#]] = 1)&, 2 Range[n] ];
  2287.         Scan[
  2288.             (e[[#[[1]], #[[2]]-1]] = e[[#[[2]],#[[1]]-1]] = Infinity)&,
  2289.             2 ToUnorderedPairs[g]
  2290.         ];
  2291.         Graph[e,Apply[Join,Map[({#,#})&,Vertices[g]]]]
  2292.     ]
  2293.  
  2294. VertexConnectivity[g_Graph] :=
  2295.     Module[{p=VertexConnectivityGraph[g],k=V[g],i=0,notedges},
  2296.         notedges = ToUnorderedPairs[ GraphComplement[g] ];
  2297.         While[ i++ <= k,
  2298.             k = Min[
  2299.                 Map[
  2300.                     (NetworkFlow[p,2 #[[1]],2 #[[2]]-1])&,
  2301.                     Select[notedges,(First[#]==i)&]
  2302.                 ],
  2303.                 k
  2304.             ]
  2305.         ];
  2306.         k
  2307.     ]
  2308.  
  2309. Harary[k_?EvenQ, n_Integer] := CirculantGraph[n,Range[k/2]]
  2310.  
  2311. Harary[k_?OddQ, n_?EvenQ] := CirculantGraph[n,Append[Range[k/2],n/2]]
  2312.  
  2313. Harary[k_?OddQ, n_?OddQ] :=
  2314.     Module[{g=Harary[k-1,n],i},
  2315.         FromUnorderedPairs[
  2316.             Join[
  2317.                 ToUnorderedPairs[g],
  2318.                 { {1,(n+1)/2}, {1,(n+3)/2} },
  2319.                 Table [ {i,i+(n+1)/2}, {i,2,(n-1)/2} ]
  2320.             ],
  2321.             Vertices[g]
  2322.         ]
  2323.     ]
  2324.  
  2325. IdenticalQ[g_Graph,h_Graph] := Edges[g] === Edges[h]
  2326.  
  2327. IsomorphismQ[g_Graph,h_Graph,p_List] := False    /;
  2328.         (V[g]!=V[h]) || !PermutationQ[p] || (Length[p] != V[g])
  2329.  
  2330. IsomorphismQ[g_Graph,h_Graph,p_List] := IdenticalQ[g, InduceSubgraph[h,p] ]
  2331.  
  2332. Isomorphism[g_Graph,h_Graph,flag_:One] := {}    /; (V[g] != V[h]) 
  2333.  
  2334. Isomorphism[g_Graph,h_Graph,flag_:One] :=
  2335.     Module[{eg=Edges[g],eh=Edges[h],equiv=Equivalences[g,h]},
  2336.         If [!MemberQ[equiv,{}],
  2337.             Backtrack[
  2338.                 equiv,
  2339.                 (IdenticalQ[InduceSubgraph[g,Range[Length[#]]],
  2340.                         InduceSubgraph[h,#] ] &&
  2341.                  !MemberQ[Drop[#,-1],Last[#]])&,
  2342.                 (IsomorphismQ[g,h,#])&,
  2343.                 flag
  2344.             ],
  2345.             {}
  2346.         ]
  2347.     ]
  2348.  
  2349. IsomorphicQ[g_Graph,h_Graph] := True /; IdenticalQ[g,h]
  2350. IsomorphicQ[g_Graph,h_Graph] := ! SameQ[ Isomorphism[g,h], {}]
  2351.  
  2352. Equivalences[g_Graph,h_Graph] :=
  2353.     Equivalences[ AllPairsShortestPath[g], AllPairsShortestPath[h]]
  2354.  
  2355. Equivalences[g_List,h_List] :=
  2356.     Module[{dg=Map[Sort,g],dh=Map[Sort,h],s,i},
  2357.         Table[
  2358.             Flatten[Position[dh,_?(Function[s,SameQ[s,dg[[i]] ]])]],
  2359.             {i,Length[dg]}
  2360.         ]
  2361.     ] /; Length[g] == Length[h]
  2362.  
  2363. Automorphisms[g_Graph,flag_:All] :=
  2364.     Module[{s=AllPairsShortestPath[g]},
  2365.         Backtrack[
  2366.             Equivalences[s,s],
  2367.             (IdenticalQ[InduceSubgraph[g,Range[Length[#]]],
  2368.                     InduceSubgraph[g,#] ] &&
  2369.              !MemberQ[Drop[#,-1],Last[#]])&,
  2370.             (IsomorphismQ[g,g,#])&,
  2371.             flag
  2372.         ]
  2373.     ]
  2374.  
  2375. SelfComplementaryQ[g_Graph] := IsomorphicQ[g, GraphComplement[g]]
  2376.  
  2377. FindCycle[g_Graph,flag_:Undirected] :=
  2378.      Module[{edge,n=V[g],x,queue,v,seen,parent},
  2379.        edge=ToAdjacencyLists[g];
  2380.        For[ v = 1, v <= n, v++,
  2381.            parent=Table[n+1,{n}]; parent[[v]] = 0;
  2382.            seen = {}; queue = {v};
  2383.            While[ queue != {},
  2384.                {x,queue} = {First[queue], Rest[queue]};
  2385.                AppendTo[seen,x];
  2386.                If[ SameQ[ flag, Undirected],
  2387.                    Scan[ (If[ parent[[x]] != #, parent[[#]]=x])&, edge[[x]] ],
  2388.                    Scan[ (parent[[#]]=x)&, edge[[x]]]
  2389.                ];
  2390.                If[ SameQ[flag,Undirected],
  2391.                    If[ MemberQ[ edge[[x]],v ] && parent[[x]] != v,
  2392.                        Return[ FromParent[parent,x] ]
  2393.                    ],
  2394.                    If[ MemberQ[ edge[[x]],v ],
  2395.                        Return[ FromParent[parent,x] ]
  2396.                    ]
  2397.                ];
  2398.                queue = Join[ Complement[ edge[[x]], seen], queue]
  2399.            ]
  2400.        ];
  2401.      {}
  2402.      ]
  2403.  
  2404. FromParent[parent_List,s_Integer] :=
  2405.     Module[{i=s,lst={s}},
  2406.         While[!MemberQ[lst,(i=parent[[i]])], PrependTo[lst,i] ];
  2407.         PrependTo[lst,i];
  2408.         Take[lst, Flatten[Position[lst,i]]]
  2409.     ]
  2410.  
  2411. AcyclicQ[g_Graph,flag_:Undirected] := SameQ[FindCycle[g,flag],{}]
  2412.  
  2413. TreeQ[g_Graph] := ConnectedQ[g] && (M[g] == V[g]-1)
  2414.  
  2415. ExtractCycles[gi_Graph,flag_:Undirected] := 
  2416.     Module[{g=gi,cycles={},c},
  2417.         While[!SameQ[{}, c=FindCycle[g,flag]],
  2418.             PrependTo[cycles,c];
  2419.             g = DeleteCycle[g,c,flag];
  2420.         ];
  2421.         cycles
  2422.     ]
  2423.  
  2424. DeleteCycle[g_Graph,cycle_List,flag_:Undirected] :=
  2425.     Module[{newg=g},
  2426.         Scan[(newg=DeleteEdge[newg,#,flag])&, Partition[cycle,2,1] ];
  2427.         newg
  2428.     ]
  2429.  
  2430. Girth[g_Graph] := 
  2431.     Module[{v,dist,queue,n=V[g],girth=Infinity,parent,e=ToAdjacencyLists[g],x},
  2432.         Do [
  2433.             dist = parent = Table[Infinity, {n}];
  2434.             dist[[v]] = parent[[v]] = 0;
  2435.             queue = {v};
  2436.             While [queue != {},
  2437.                 {x,queue} = {First[queue],Rest[queue]};
  2438.                 Scan[
  2439.                     (If [ (dist[[#]]+dist[[x]]<girth) &&
  2440.                                (parent[[x]] != #),
  2441.                         girth=dist[[#]]+dist[[x]] + 1,
  2442.                       If [dist[[#]]==Infinity,
  2443.                         dist[[#]] = dist[[x]] + 1;
  2444.                         parent[[#]] = x;
  2445.                         If [2 dist[[#]] < girth-1,
  2446.                             AppendTo[queue,#] ]
  2447.                     ]])&,
  2448.                     e[[ x ]]
  2449.                 ];
  2450.             ],
  2451.             {v,n}
  2452.         ];
  2453.         girth
  2454.     ] /; SimpleQ[g]
  2455.  
  2456. EulerianQ[g_Graph,Directed] :=
  2457.     ConnectedQ[g,Undirected] && (InDegree[g] === OutDegree[g])
  2458.  
  2459. EulerianQ[g_Graph,flag_:Undirected] := ConnectedQ[g,Undirected] && 
  2460.     UndirectedQ[g] && Apply[And,Map[EvenQ,DegreeSequence[g]]]
  2461.  
  2462. OutDegree[Graph[e_List,_],n_Integer] := Length[ Select[ e[[n]], (# != 0)& ] ]
  2463. OutDegree[g_Graph] := Map[ (OutDegree[g,#])&, Range[V[g]] ]
  2464.  
  2465. InDegree[g_Graph,n_Integer] := OutDegree[ TransposeGraph[g], n ];
  2466. InDegree[g_Graph] := Map[ (InDegree[g,#])&, Range[V[g]] ]
  2467.  
  2468. TransposeGraph[Graph[g_List,v_List]] := Graph[ Transpose[g], v ]
  2469.  
  2470. EulerianCycle[g_Graph,flag_:Undirected] :=
  2471.     Module[{euler,c,cycles,v},
  2472.         cycles = Map[(Drop[#,-1])&, ExtractCycles[g,flag]];
  2473.         {euler, cycles} = {First[cycles], Rest[cycles]};
  2474.         Do [
  2475.             c = First[ Select[cycles, (Intersection[euler,#]=!={})&] ];
  2476.             v = First[Intersection[euler,c]];
  2477.             euler = Join[
  2478.                 RotateLeft[c, Position[c,v] [[1,1]] ],
  2479.                 RotateLeft[euler, Position[euler,v] [[1,1]] ]
  2480.             ];
  2481.             cycles = Complement[cycles,{c}],
  2482.             {Length[cycles]}
  2483.         ];
  2484.         Append[euler, First[euler]]
  2485.     ] /; EulerianQ[g,flag]
  2486.  
  2487. DeBruijnSequence[alph_List,n_Integer] :=
  2488.         Module[{states = Strings[alph,n-1]},
  2489.                 Rest[ Map[
  2490.                         (First[ states[[#]] ])&,
  2491.                         EulerianCycle[
  2492.                                 MakeGraph[
  2493.                                         states,
  2494.                                         (Module[{i},
  2495.                                          MemberQ[
  2496.                                                 Table[
  2497.                                                         Append[Rest[#1],alph[[i]]],
  2498.                                                         {i,Length[alph]}
  2499.                                                 ],
  2500.                                                 #2
  2501.                                          ]
  2502.                                         ])&
  2503.                                 ],
  2504.                                 Directed
  2505.                         ]
  2506.                 ] ]
  2507.         ] /; n>=2
  2508.  
  2509. DeBruijnSequence[alph_List,n_Integer] := alph /; n==1
  2510.  
  2511. HamiltonianQ[g_Graph] := False /; !BiconnectedQ[g]
  2512. HamiltonianQ[g_Graph] := HamiltonianCycle[g] != {}
  2513.  
  2514. HamiltonianCycle[g_Graph,flag_:One] :=
  2515.     Module[{s={1},all={},done,adj=Edges[g],e=ToAdjacencyLists[g],x,v,ind,n=V[g]},
  2516.         ind=Table[1,{n}];
  2517.         While[ Length[s] > 0,
  2518.             v = Last[s];
  2519.             done = False;
  2520.             While[ ind[[v]] <= Length[e[[v]]] && !done,
  2521.                 If[!MemberQ[s,(x = e[[v,ind[[v]]++]])], done=True]
  2522.             ];
  2523.             If[ done, AppendTo[s,x], s=Drop[s,-1]; ind[[v]] = 1];
  2524.             If[(Length[s] == n),
  2525.                 If [(adj[[x,1]]>0),
  2526.                     AppendTo[all,Append[s,First[s]]];
  2527.                     If [SameQ[flag,All],
  2528.                         s=Drop[s,-1],
  2529.                         all = Flatten[all]; s={}
  2530.                     ],
  2531.                     s = Drop[s,-1]
  2532.                 ]
  2533.             ]
  2534.         ];
  2535.         all
  2536.     ]
  2537.  
  2538. TravelingSalesman[g_Graph] :=
  2539.     Module[{v,s={1},sol={},done,cost,g1,e=ToAdjacencyLists[g],x,ind,best,n=V[g]},
  2540.         ind=Table[1,{n}];
  2541.         g1 = PathConditionGraph[g];
  2542.         best = Infinity;
  2543.         While[ Length[s] > 0,
  2544.             v = Last[s];
  2545.             done = False;
  2546.             While[ ind[[v]] <= Length[e[[v]]] && !done,
  2547.                 x = e[[v,ind[[v]]++]];
  2548.                 done = (best > CostOfPath[g1,Append[s,x]]) &&
  2549.                     !MemberQ[s,x]
  2550.             ];
  2551.             If[done, AppendTo[s,x], s=Drop[s,-1]; ind[[v]] = 1];
  2552.             If[(Length[s] == n),
  2553.                 cost = CostOfPath[g1, Append[s,First[s]]];
  2554.                 If [(cost < best), sol = s; best = cost ];
  2555.                 s = Drop[s,-1]
  2556.             ]
  2557.         ];
  2558.         Append[sol,First[sol]]
  2559.     ]
  2560.  
  2561. CostOfPath[Graph[g_,_],p_List] := Apply[Plus, Map[(Element[g,#])&,Partition[p,2,1]] ]
  2562.  
  2563. Element[a_List,{index___}] := a[[ index ]]
  2564.  
  2565. TriangleInequalityQ[e_?SquareMatrixQ] :=
  2566.     Module[{i,j,k,n=Length[e],flag=True},
  2567.         Do [
  2568.  
  2569.             If[(e[[i,k]]!=0) && (e[[k,j]]!=0) && (e[[i,j]]!=0),
  2570.                 If[e[[i,k]]+e[[k,j]]<e[[i,j]],
  2571.                     flag = False;
  2572.                 ]
  2573.             ],
  2574.             {i,n},{j,n},{k,n}
  2575.         ];
  2576.         flag
  2577.     ]
  2578.  
  2579. TriangleInequalityQ[g_Graph] := TriangleInequalityQ[Edges[g]]
  2580.  
  2581. TravelingSalesmanBounds[g_Graph] := {LowerBoundTSP[g], UpperBoundTSP[g]}
  2582.  
  2583. UpperBoundTSP[g_Graph] :=
  2584.     CostOfPath[g, Append[DepthFirstTraversal[MinimumSpanningTree[g],1],1]]
  2585.  
  2586. LowerBoundTSP[g_Graph] := Apply[Plus, Map[Min,ReplaceAll[Edges[g],0->Infinity]]]
  2587.  
  2588. PartialOrderQ[g_Graph] := ReflexiveQ[g] && AntiSymmetricQ[g] && TransitiveQ[g]
  2589.  
  2590. TransitiveQ[g_Graph] := IdenticalQ[g,TransitiveClosure[g]]
  2591.  
  2592. ReflexiveQ[Graph[g_List,_]] := 
  2593.     Module[{i},
  2594.         Apply[And, Table[(g[[i,i]]!=0),{i,Length[g]}] ]
  2595.     ]
  2596.  
  2597. AntiSymmetricQ[g_Graph] := 
  2598.     Module[{e = Edges[g], g1 = RemoveSelfLoops[g]},
  2599.         Apply[And, Map[(Element[e,Reverse[#]]==0)&,ToOrderedPairs[g1]] ]
  2600.     ]
  2601.  
  2602. TransitiveClosure[g_Graph] :=
  2603.     Module[{i,j,k,e=Edges[g],n=V[g]},
  2604.         Do [
  2605.             If[ e[[j,i]] != 0,
  2606.                 Do [
  2607.                     If[ e[[i,k]] != 0, e[[j,k]]=1],
  2608.                     {k,n}
  2609.                 ]
  2610.             ],
  2611.             {i,n},{j,n}
  2612.         ];
  2613.         Graph[e,Vertices[g]]
  2614.     ]
  2615.  
  2616. TransitiveReduction[g_Graph] :=
  2617.     Module[{closure=reduction=Edges[g],i,j,k,n=V[g]},
  2618.         Do[
  2619.             If[ closure[[i,j]]!=0 && closure[[j,k]]!=0 &&
  2620.                  reduction[[i,k]]!=0 && (i!=j) && (j!=k) && (i!=k),
  2621.                     reduction[[i,k]] = 0
  2622.             ],
  2623.             {i,n},{j,n},{k,n}
  2624.         ];
  2625.         Graph[reduction,Vertices[g]]
  2626.     ] /; AcyclicQ[RemoveSelfLoops[g],Directed] 
  2627.  
  2628. TransitiveReduction[g_Graph] :=
  2629.     Module[{reduction=Edges[g],i,j,k,n=V[g]},
  2630.         Do[
  2631.             If[ reduction[[i,j]]!=0 && reduction[[j,k]]!=0 &&
  2632.                  reduction[[i,k]]!=0 && (i!=j) && (j!=k) && (i!=k),
  2633.                     reduction[[i,k]] = 0
  2634.             ],
  2635.             {i,n},{j,n},{k,n}
  2636.         ];
  2637.         Graph[reduction,Vertices[g]]
  2638.     ] 
  2639.  
  2640. HasseDiagram[g_Graph] :=
  2641.     Module[{r,rank,m,stages,freq=Table[0,{V[g]}]},
  2642.         r = TransitiveReduction[ RemoveSelfLoops[g] ];
  2643.         rank = RankGraph[
  2644.                 MakeUndirected[r],
  2645.                 Select[Range[V[g]],(InDegree[r,#]==0)&]
  2646.         ];
  2647.         m = Max[rank];
  2648.         rank = MapAt[(m)&,rank,Position[OutDegree[r],0]];
  2649.         stages = Distribution[ rank ];
  2650.         Graph[
  2651.             Edges[r],
  2652.             Table[
  2653.                 m = ++ freq[[ rank[[i]] ]];
  2654.                 {(m-1) + (1-stages[[rank[[i]] ]])/2, rank[[i]]},
  2655.                 {i,V[g]}
  2656.             ]
  2657.         ]
  2658.     ] /; AcyclicQ[RemoveSelfLoops[g],Directed]
  2659.  
  2660. TopologicalSort[g_Graph] :=
  2661.     Module[{g1 = RemoveSelfLoops[g],e,indeg,zeros,v},
  2662.         e=ToAdjacencyLists[g1];
  2663.         indeg=InDegree[g1];
  2664.         zeros = Flatten[ Position[indeg, 0] ];
  2665.         Table [
  2666.             {v,zeros}={First[zeros],Rest[zeros]};
  2667.             Scan[
  2668.                 ( indeg[[#]]--;
  2669.                   If[indeg[[#]]==0, AppendTo[zeros,#]] )&,
  2670.                 e[[ v ]]
  2671.             ];
  2672.             v,
  2673.             {V[g]}
  2674.         ]
  2675.     ] /; AcyclicQ[RemoveSelfLoops[g],Directed]
  2676.  
  2677. ChromaticPolynomial[g_Graph,z_] := 0 /; Identical[g,K[0]]
  2678.  
  2679. ChromaticPolynomial[g_Graph,z_] :=
  2680.     Module[{i}, Product[z-i, {i,0,V[g]-1}] ] /; CompleteQ[g]
  2681.  
  2682. ChromaticPolynomial[g_Graph,z_] := z ( z - 1 ) ^ (V[g]-1) /; TreeQ[g]
  2683.  
  2684. ChromaticPolynomial[g_Graph,z_] :=
  2685.     If [M[g]>Binomial[V[g],2]/2, ChromaticDense[g,z], ChromaticSparse[g,z]]
  2686.  
  2687. ChromaticSparse[g_Graph,z_] := z^V[g] /; EmptyQ[g]
  2688. ChromaticSparse[g_Graph,z_] :=
  2689.     Module[{i=1, v, e=Edges[g], none=Table[0,{V[g]}]},
  2690.             While[e[[i]] === none, i++];
  2691.             v = Position[e[[i]],1] [[1,1]];
  2692.         ChromaticSparse[ DeleteEdge[g,{i,v}], z ] -
  2693.             ChromaticSparse[ Contract[g,{i,v}], z ]
  2694.     ]
  2695.  
  2696. ChromaticDense[g_Graph,z_] := ChromaticPolynomial[g,z] /; CompleteQ[g]
  2697. ChromaticDense[g_Graph,z_] :=
  2698.     Module[
  2699.         {i=1, v, e=Edges[g], all=Join[Table[1,{V[g]-1}],{0}] },
  2700.         While[e[[i]] === RotateRight[all,i], i++];
  2701.         v = Last[ Position[e[[i]],0] ] [[1]];
  2702.         ChromaticDense[ AddEdge[g,{i,v}], z ] +
  2703.             ChromaticDense[ Contract[g,{i,v}], z ]
  2704.     ]
  2705.  
  2706. ChromaticNumber[g_Graph] :=
  2707.     Block[{ways, z},
  2708.         ways[z_] = ChromaticPolynomial[g,z];
  2709.         For [z=0, z<=V[g], z++,
  2710.             If [ways[z] > 0, Return[z]]
  2711.         ]
  2712.     ]
  2713.  
  2714. TwoColoring[g_Graph] := 
  2715.     Module[{queue,elem,edges,col,flag=True,colored=Table[0,{V[g]}]},
  2716.         edges = ToAdjacencyLists[g];
  2717.         While[ MemberQ[colored,0],
  2718.             queue = First[ Position[colored,0] ];
  2719.             colored[[ First[queue] ]] = 1;
  2720.             While[ queue != {},
  2721.                 elem = First[queue];
  2722.                 col = colored[[elem]];
  2723.                 Scan[
  2724.                     (Switch[colored[[ # ]],
  2725.                         col, flag = False,
  2726.                         0, AppendTo[queue, # ];
  2727.                            colored[[#]] = Mod[col,2]+1
  2728.                     ])&,
  2729.                     edges[[elem]]
  2730.                 ];
  2731.                 queue = Rest[queue];
  2732.             ]
  2733.         ];
  2734.         If [!flag, colored[[1]] = 0];
  2735.         colored
  2736.     ]
  2737.  
  2738. BipartiteQ[g_Graph] := ! MemberQ[ TwoColoring[g], 0 ]
  2739.  
  2740. VertexColoring[g_Graph] :=
  2741.     Module[{v,l,n=V[g],e=ToAdjacencyLists[g],x,color=Table[0,{V[g]}]},
  2742.         v = Map[(Apply[Plus,#])&, Edges[g]];
  2743.         Do[
  2744.             l = MaximumColorDegreeVertices[e,color];
  2745.             x = First[l];
  2746.             Scan[(If[ v[[#]] > v[[x]], x = #])&, l];
  2747.             color[[x]] = Min[
  2748.                 Complement[ Range[n], color[[ e[[x]] ]] ]
  2749.             ],
  2750.             {V[g]}
  2751.         ];
  2752.         color
  2753.     ]
  2754.  
  2755. MaximumColorDegreeVertices[e_List,color_List] :=
  2756.     Module[{n=Length[color],l,i,x},
  2757.         l = Table[ Count[e[[i]], _?(Function[x,color[[x]]!=0])], {i,n}];
  2758.         Do [ 
  2759.             If [color[[i]]!=0, l[[i]] = -1],
  2760.             {i,n}
  2761.         ];
  2762.         Flatten[ Position[ l, Max[l] ] ]
  2763.     ]
  2764.  
  2765. EdgeColoring[g_Graph] := VertexColoring[ LineGraph[g] ]
  2766.  
  2767. EdgeChromaticNumber[g_Graph] := ChromaticNumber[ LineGraph[g] ]
  2768.  
  2769. CliqueQ[g_Graph,clique_List] :=
  2770.     IdenticalQ[ K[Length[clique]], InduceSubgraph[g,clique] ] /; SimpleQ[g]
  2771.  
  2772. MaximumClique[g_Graph] := {} /; g === K[0]
  2773.  
  2774. MaximumClique[g_Graph] :=
  2775.     Module[{d = Degrees[g],i,clique=Null,k},
  2776.         i = Max[d];
  2777.         While[(SameQ[clique,Null]),
  2778.             k = K[i+1];
  2779.             clique = FirstExample[
  2780.                 KSubsets[Flatten[Position[d,_?((#>=i)&)]], i+1],
  2781.                 (IdenticalQ[k,InduceSubgraph[g,#]])&
  2782.             ];
  2783.             i--;
  2784.         ];
  2785.         clique
  2786.     ]
  2787.  
  2788. FirstExample[list_List, predicate_] := Scan[(If [predicate[#],Return[#]])&,list]
  2789.  
  2790. VertexCoverQ[g_Graph,vc_List] :=
  2791.     CliqueQ[ GraphComplement[g], Complement[Range[V[g]], vc] ]
  2792.  
  2793. MinimumVertexCover[g_Graph] :=
  2794.     Complement[ Range[V[g]], MaximumClique[ GraphComplement[g] ] ]
  2795.  
  2796. IndependentSetQ[g_Graph,indep_List] :=
  2797.     VertexCoverQ[ g, Complement[ Range[V[g]], indep] ]
  2798.  
  2799. MaximumIndependentSet[g_Graph] := Complement[Range[V[g]], MinimumVertexCover[g]]
  2800.  
  2801. PerfectQ[g_Graph] :=
  2802.     Apply[
  2803.         And,
  2804.         Map[(ChromaticNumber[#] == Length[MaximumClique[#]])&,
  2805.             Map[(InduceSubgraph[g,#])&, Subsets[Range[V[g]]] ] ]
  2806.     ]
  2807.  
  2808. Dijkstra[g_Graph,start_Integer] := First[ Dijkstra[g,{start}] ]
  2809.  
  2810. Dijkstra[g_Graph, l_List] :=
  2811.     Module[{x,start,e=ToAdjacencyLists[g],i,p,parent,untraversed},
  2812.         p=Edges[PathConditionGraph[g]];
  2813.         Table[
  2814.             start = l[[i]];
  2815.             parent=untraversed=Range[V[g]];
  2816.             dist = p[[start]]; dist[[start]] = 0;
  2817.             Scan[ (parent[[#]] = start)&, e[[start]] ];
  2818.             While[ untraversed != {} ,
  2819.                 x = First[untraversed];
  2820.                 Scan[(If [dist[[#]]<dist[[x]],x=#])&, untraversed];
  2821.                 untraversed = Complement[untraversed,{x}];
  2822.                 Scan[
  2823.                     (If[dist[[#]] > dist[[x]]+p[[x,#]],
  2824.                         dist[[#]] = dist[[x]]+p[[x,#]];
  2825.                         parent[[#]] = x ])&,
  2826.                     e[[x]]
  2827.                 ];
  2828.             ];
  2829.             {parent, dist},
  2830.             {i,Length[l]}
  2831.         ]
  2832.     ]
  2833.  
  2834. ShortestPath[g_Graph,s_Integer,e_Integer] := 
  2835.     Module[{parent=First[Dijkstra[g,s]],i=e,lst={e}},
  2836.         While[ (i != s) && (i != parent[[i]]),
  2837.             PrependTo[lst,parent[[i]]];
  2838.             i = parent[[i]]
  2839.         ];
  2840.         If[ i == s, lst, {}]
  2841.     ]
  2842.  
  2843. ShortestPathSpanningTree[g_Graph,s_Integer] :=
  2844.     Module[{parent=First[Dijkstra[g,s]],i},
  2845.         FromUnorderedPairs[
  2846.             Map[({#,parent[[#]]})&, Complement[Range[V[g]],{s}]],
  2847.             Vertices[g]
  2848.         ]
  2849.     ]
  2850.  
  2851. AllPairsShortestPath[g_Graph] :=
  2852.     Module[{p=Edges[ PathConditionGraph[g] ],i,j,k,n=V[g]},
  2853.         Do [
  2854.             p = Table[Min[p[[i,k]]+p[[k,j]],p[[i,j]]],{i,n},{j,n}],
  2855.             {k,n}
  2856.         ];
  2857.         p
  2858.     ] /; Min[Edges[g]] < 0
  2859.  
  2860. AllPairsShortestPath[g_Graph] := Map[ Last, Dijkstra[g, Range[V[g]]]]
  2861.  
  2862. PathConditionGraph[Graph[e_,v_]] := RemoveSelfLoops[Graph[ReplaceAll[e,0->Infinity],v]]
  2863.  
  2864. GraphPower[g_Graph,1] := g
  2865.  
  2866. GraphPower[g_Graph,n_Integer] :=
  2867.     Module[{prod=power=p=Edges[g]},
  2868.         Do [
  2869.             prod = prod . p;
  2870.             power = prod + power,
  2871.             {n-1}
  2872.         ];
  2873.         Graph[power, Vertices[g]]
  2874.     ]
  2875.  
  2876. InitializeUnionFind[n_Integer] := Module[{i}, Table[{i,1},{i,n}] ]
  2877.  
  2878. FindSet[n_Integer,s_List] := If [n == s[[n,1]], n, FindSet[s[[n,1]],s] ]
  2879.  
  2880. UnionSet[a_Integer,b_Integer,s_List] :=
  2881.     Module[{sa=FindSet[a,s], sb=FindSet[b,s], set=s},
  2882.         If[ set[[sa,2]] < set[[sb,2]], {sa,sb} = {sb,sa} ];
  2883.         set[[sa]] = {sa, Max[ set[[sa,2]], set[[sb,2]]+1 ]};
  2884.         set[[sb]] = {sa, set[[sb,2]]};
  2885.         set
  2886.     ]
  2887.  
  2888. MinimumSpanningTree[g_Graph] :=
  2889.     Module[{edges=Edges[g],set=InitializeUnionFind[V[g]]},
  2890.         FromUnorderedPairs[
  2891.             Select [
  2892.                 Sort[
  2893.                     ToUnorderedPairs[g],
  2894.                     (Element[edges,#1]<=Element[edges,#2])&
  2895.                 ],
  2896.                 (If [FindSet[#[[1]],set] != FindSet[#[[2]],set],
  2897.                     set=UnionSet[#[[1]],#[[2]],set]; True,
  2898.                     False
  2899.                 ])&
  2900.             ],
  2901.             Vertices[g]
  2902.         ]
  2903.     ] /; UndirectedQ[g]
  2904.  
  2905. MaximumSpanningTree[g_Graph] := MinimumSpanningTree[Graph[-Edges[g],Vertices[g]]]
  2906.  
  2907. Cofactor[m_List,{i_Integer,j_Integer}] :=
  2908.     (-1)^(i+j) * Det[ Drop[ Transpose[ Drop[Transpose[m],{j,j}] ], {i,i}] ]
  2909.  
  2910. NumberOfSpanningTrees[Graph[g_List,_]] :=
  2911.     Cofactor[ DiagonalMatrix[Map[(Apply[Plus,#])&,g]] - g, {1,1}]
  2912.  
  2913. NetworkFlow[g_Graph,source_Integer,sink_Integer] :=
  2914.     Block[{flow=NetworkFlowEdges[g,source,sink], i},
  2915.         Sum[flow[[i,sink]], {i,V[g]}]
  2916.     ]
  2917.  
  2918.  
  2919. NetworkFlowEdges[g_Graph,source_Integer,sink_Integer] :=
  2920.     Block[{e=Edges[g], x, y, flow=Table[0,{V[g]},{V[g]}], p, m},
  2921.         While[ !SameQ[p=AugmentingPath[g,source,sink], {}],
  2922.             m = Min[Map[({x,y}=#[[1]]; 
  2923.                  If[SameQ[#[[2]],f],e[[x,y]]-flow[[x,y]],
  2924.                     flow[[x,y]]])&,p]];
  2925.             Scan[    
  2926.                 ({x,y}=#[[1]];
  2927.                  If[ SameQ[#[[2]],f],
  2928.                     flow[[x,y]]+=m,flow[[x,y]]-=m])&,
  2929.                  p
  2930.             ]
  2931.         ];
  2932.         flow
  2933.     ]
  2934.  
  2935. AugmentingPath[g_Graph,src_Integer,sink_Integer] :=
  2936.     Block[{l={src},lab=Table[0,{V[g]}],v,c=Edges[g],e=ToAdjacencyLists[g]},
  2937.         lab[[src]] = start;
  2938.         While[l != {} && (lab[[sink]]==0),
  2939.             {v,l} = {First[l],Rest[l]};
  2940.             Scan[ (If[ c[[v,#]] - flow[[v,#]] > 0 && lab[[#]] == 0,
  2941.                 lab[[#]] = {v,f}; AppendTo[l,#]])&,
  2942.                 e[[v]]
  2943.             ];
  2944.             Scan[ (If[ flow[[#,v]] > 0 && lab[[#]] == 0,
  2945.                 lab[[#]] = {v,b}; AppendTo[l,#]] )&,
  2946.                 Select[Range[V[g]],(c[[#,v]] > 0)&]
  2947.             ];
  2948.         ];
  2949.         FindPath[lab,src,sink]
  2950.     ]
  2951.  
  2952. FindPath[l_List,v1_Integer,v2_Integer] :=
  2953.     Block[{x=l[[v2]],y,z=v2,lst={}},
  2954.         If[SameQ[x,0], Return[{}]];
  2955.         While[!SameQ[x, start],
  2956.             If[ SameQ[x[[2]],f],
  2957.                 PrependTo[lst,{{ x[[1]], z }, f}],
  2958.                 PrependTo[lst,{{ z, x[[1]] }, b}]
  2959.             ];
  2960.             z = x[[1]]; x = l[[z]];
  2961.         ];
  2962.         lst
  2963.     ]
  2964.  
  2965. BipartiteMatching[g_Graph] :=
  2966.     Module[{p,v1,v2,coloring=TwoColoring[g],n=V[g]},
  2967.         v1 = Flatten[Position[coloring,1]];
  2968.         v2 = Flatten[Position[coloring,2]];
  2969.         p = BipartiteMatchingFlowGraph[g,v1,v2];
  2970.         flow = NetworkFlowEdges[p,V[g]+1,V[g]+2];
  2971.         Select[ToOrderedPairs[Graph[flow,Vertices[p]]], (Max[#]<=n)&]
  2972.     ] /; BipartiteQ[g]
  2973.  
  2974. BipartiteMatchingFlowGraph[g_Graph,v1_List,v2_List] :=
  2975.     Module[{edges = Table[0,{V[g]+2},{V[g]+2}],i,e=ToAdjacencyLists[g]},
  2976.         Do[ 
  2977.                 Scan[ (edges[[v1[[i]],#]] = 1)&, e[[ v1[[i]] ]] ],
  2978.             {i,Length[v1]}
  2979.         ];
  2980.         Scan[(edges[[V[g] + 1, #]] = 1)&, v1];
  2981.         Scan[(edges[[#, V[g] + 2]] = 1)&, v2];
  2982.         Graph[edges,RandomVertices[V[g] + 2] ]
  2983.     ]
  2984.  
  2985. MinimumChainPartition[g_Graph] :=
  2986.     ConnectedComponents[
  2987.         FromUnorderedPairs[
  2988.             Map[(#-{0,V[g]})&, BipartiteMatching[DilworthGraph[g]]],
  2989.             Vertices[g]
  2990.         ]
  2991.     ]
  2992.  
  2993. MaximumAntichain[g_Graph] := MaximumIndependentSet[TransitiveClosure[g]]
  2994.  
  2995. DilworthGraph[g_Graph] :=
  2996.     FromUnorderedPairs[
  2997.         Map[
  2998.             (#+{0,V[g]})&,
  2999.             ToOrderedPairs[RemoveSelfLoops[TransitiveReduction[g]]]
  3000.         ]
  3001.     ]
  3002.  
  3003. MaximalMatching[g_Graph] :=
  3004.     Module[{match={}},
  3005.         Scan[
  3006.             (If [Intersection[#,match]=={}, match=Join[match,#]])&,
  3007.             ToUnorderedPairs[g]
  3008.         ];
  3009.         Partition[match,2]
  3010.     ]
  3011.  
  3012. StableMarriage[mpref_List,fpref_List] :=
  3013.     Module[{n=Length[mpref],freemen,cur,i,w,husband},
  3014.         freemen = Range[n];
  3015.         cur = Table[1,{n}];
  3016.         husband = Table[n+1,{n}];
  3017.         While[ freemen != {},
  3018.             {i,freemen}={First[freemen],Rest[freemen]};
  3019.             w = mpref[[ i,cur[[i]] ]];
  3020.             If[BeforeQ[ fpref[[w]], i, husband[[w]] ], 
  3021.                 If[husband[[w]] != n+1,
  3022.                     AppendTo[freemen,husband[[w]] ]
  3023.                 ];
  3024.                 husband[[w]] = i,
  3025.                 cur[[i]]++;
  3026.                 AppendTo[freemen,i]
  3027.             ];
  3028.         ];
  3029.         InversePermutation[ husband ]
  3030.     ] /; Length[mpref] == Length[fpref]
  3031.  
  3032. BeforeQ[l_List,a_,b_] :=
  3033.     If [First[l]==a, True, If [First[l]==b, False, BeforeQ[Rest[l],a,b] ] ]
  3034.  
  3035. PlanarQ[g_Graph] :=
  3036.     Apply[
  3037.         And,
  3038.         Map[(PlanarQ[InduceSubgraph[g,#]])&, ConnectedComponents[g]]
  3039.     ] /; !ConnectedQ[g]
  3040.  
  3041. PlanarQ[g_Graph] := False /;  (M[g] > 3 V[g]-6) && (V[g] > 2)
  3042. PlanarQ[g_Graph] := True /;   (M[g] < V[g] + 3)
  3043. PlanarQ[g_Graph] := PlanarGivenCycle[ g, Rest[FindCycle[g]] ]
  3044.  
  3045. PlanarGivenCycle[g_Graph, cycle_List] :=
  3046.     Module[{b, j, i},
  3047.         {b, j} = FindBridge[g, cycle];
  3048.         If[ InterlockQ[j, cycle],
  3049.             False,
  3050.             Apply[And, Table[SingleBridgeQ[b[[i]],j[[i]]], {i,Length[b]}]]
  3051.         ]
  3052.     ]
  3053.  
  3054. SingleBridgeQ[b_Graph, {_}] := PlanarQ[b]
  3055.  
  3056. SingleBridgeQ[b_Graph, j_List] :=
  3057.     PlanarGivenCycle[ JoinCycle[b,j],
  3058.         Join[ ShortestPath[b,j[[1]],j[[2]]], Drop[j,2]] ]
  3059.  
  3060. JoinCycle[g1_Graph, cycle_List] :=
  3061.     Module[{g=g1},
  3062.         Scan[(g = AddEdge[g,#])&, Partition[cycle,2,1] ];
  3063.         AddEdge[g,{First[cycle],Last[cycle]}]
  3064.     ]
  3065.  
  3066. FindBridge[g_Graph, cycle_List] :=
  3067.     Module[{rg = RemoveCycleEdges[g, cycle], b, bridge, j},
  3068.     b = Map[
  3069.         (IsolateSubgraph[rg,g,cycle,#])&,
  3070.         Select[ConnectedComponents[rg], (Intersection[#,cycle]=={})&]
  3071.     ];
  3072.     b = Select[b, (!EmptyQ[#])&];
  3073.     j = Join[
  3074.         Map[Function[bridge,Select[cycle, MemberQ[Edges[bridge][[#]],1]&] ], b],
  3075.         Complement[
  3076.             Select[ToOrderedPairs[g],
  3077.                 (Length[Intersection[#,cycle]] == 2)&],
  3078.             Partition[Append[cycle,First[cycle]],2,1]
  3079.         ]
  3080.     ];
  3081.     {b, j}
  3082.     ]
  3083.  
  3084. RemoveCycleEdges[g_Graph, c_List] :=
  3085.     FromOrderedPairs[
  3086.         Select[ ToOrderedPairs[g], (Intersection[c,#] === {})&],
  3087.         Vertices[g]
  3088.     ]
  3089.  
  3090. IsolateSubgraph[g_Graph,orig_Graph,cycle_List,cc_List] :=
  3091.     Module[{eg=ToOrderedPairs[g], og=ToOrderedPairs[orig]},
  3092.         FromOrderedPairs[
  3093.             Join[
  3094.                 Select[eg, (Length[Intersection[cc,#]] == 2)&],
  3095.                 Select[og, (Intersection[#,cycle]!={} &&
  3096.                     Intersection[#,cc]!={})&]
  3097.             ],
  3098.             Vertices[g]
  3099.         ]
  3100.     ]
  3101.  
  3102. InterlockQ[ bl_List, c_List ] :=
  3103.     Module[{in = out = {}, code, jp, bridgelist = bl },
  3104.         While [ bridgelist != {},
  3105.             {jp, bridgelist} = {First[bridgelist],Rest[bridgelist]};
  3106.             code = Sort[ Map[(Position[c, #][[1,1]])&, jp] ];
  3107.             If[ Apply[ Or, Map[(LockQ[#,code])&, in] ],
  3108.                 If [ Apply[Or, Map[(LockQ[#,code])&, out] ],
  3109.                     Return[True],
  3110.                     AppendTo[out,code]
  3111.                 ],
  3112.                 AppendTo[in,code]
  3113.             ]
  3114.         ];
  3115.         False
  3116.     ]
  3117.  
  3118. LockQ[a_List,b_List] := Lock1Q[a,b] || Lock1Q[b,a]
  3119.  
  3120. Lock1Q[a_List,b_List] :=
  3121.     Module[{bk, aj},
  3122.         bk = Min[ Select[Drop[b,-1], (#>First[a])&] ];
  3123.         aj = Min[ Select[a, (# > bk)&] ];
  3124.         (aj < Max[b])
  3125.     ]
  3126.  
  3127. End[]
  3128.  
  3129. Protect[
  3130. AcyclicQ,
  3131. AddEdge,
  3132. AddVertex,
  3133. AllPairsShortestPath,
  3134. ArticulationVertices,
  3135. Automorphisms,
  3136. Backtrack,
  3137. BiconnectedComponents,
  3138. BiconnectedComponents,
  3139. BiconnectedQ,
  3140. BinarySearch,
  3141. BinarySubsets,
  3142. BipartiteMatching,
  3143. BipartiteQ,
  3144. BreadthFirstTraversal,
  3145. Bridges,
  3146. CartesianProduct,
  3147. CatalanNumber,
  3148. ChangeEdges,
  3149. ChangeVertices,
  3150. ChromaticNumber,
  3151. ChromaticPolynomial,
  3152. CirculantGraph,
  3153. CircularVertices,
  3154. CliqueQ,
  3155. CodeToLabeledTree,
  3156. Cofactor,
  3157. CompleteQ,
  3158. Compositions,
  3159. ConnectedComponents,
  3160. ConnectedQ,
  3161. ConstructTableau,
  3162. Contract,
  3163. CostOfPath,
  3164. Cycle,
  3165. DeBruijnSequence,
  3166. DegreeSequence,
  3167. DeleteCycle,
  3168. DeleteEdge,
  3169. DeleteFromTableau,
  3170. DeleteVertex,
  3171. DepthFirstTraversal,
  3172. DerangementQ,
  3173. Derangements,
  3174. Diameter,
  3175. Dijkstra,
  3176. DilateVertices,
  3177. DistinctPermutations,
  3178. Distribution,
  3179. DurfeeSquare,
  3180. Eccentricity,
  3181. EdgeChromaticNumber,
  3182. EdgeColoring,
  3183. EdgeConnectivity,
  3184. Edges,
  3185. Element,
  3186. EmptyGraph,
  3187. EmptyQ,
  3188. EncroachingListSet,
  3189. EquivalenceClasses,
  3190. EquivalenceRelationQ,
  3191. Equivalences,
  3192. EulerianCycle,
  3193. EulerianQ,
  3194. Eulerian,
  3195. ExactRandomGraph,
  3196. ExpandGraph,
  3197. ExtractCycles,
  3198. FerrersDiagram,
  3199. FindCycle,
  3200. FindSet,
  3201. FirstLexicographicTableau,
  3202. FromAdjacencyLists,
  3203. FromCycles,
  3204. FromInversionVector,
  3205. FromOrderedPairs,
  3206. FromUnorderedPairs,
  3207. FunctionalGraph,
  3208. Girth,
  3209. GraphCenter,
  3210. GraphComplement,
  3211. GraphDifference,
  3212. GraphIntersection,
  3213. GraphJoin,
  3214. GraphPower,
  3215. GraphProduct,
  3216. GraphSum,
  3217. GraphUnion,
  3218. GraphicQ,
  3219. GrayCode,
  3220. GridGraph,
  3221. HamiltonianCycle,
  3222. HamiltonianQ,
  3223. Harary,
  3224. HasseDiagram,
  3225. HeapSort,
  3226. Heapify,
  3227. HideCycles,
  3228. Hypercube,
  3229. IdenticalQ,
  3230. IncidenceMatrix,
  3231. IndependentSetQ,
  3232. Index,
  3233. InduceSubgraph,
  3234. InitializeUnionFind,
  3235. InsertIntoTableau,
  3236. IntervalGraph,
  3237. InversePermutation,
  3238. Inversions,
  3239. InvolutionQ,
  3240. IsomorphicQ,
  3241. IsomorphismQ,
  3242. Isomorphism,
  3243. Josephus,
  3244. KSubsets,
  3245. K,
  3246. LabeledTreeToCode,
  3247. LastLexicographicTableau,
  3248. LexicographicPermutations,
  3249. LexicographicSubsets,
  3250. LineGraph,
  3251. LongestIncreasingSubsequence,
  3252. M,
  3253. MakeGraph,
  3254. MakeSimple,
  3255. MakeUndirected,
  3256. MaximalMatching,
  3257. MaximumAntichain,
  3258. MaximumClique,
  3259. MaximumIndependentSet,
  3260. MaximumSpanningTree,
  3261. MinimumChainPartition,
  3262. MinimumChangePermutations,
  3263. MinimumSpanningTree,
  3264. MinimumVertexCover,
  3265. MultiplicationTable,
  3266. NetworkFlowEdges,
  3267. NetworkFlow,
  3268. NextComposition,
  3269. NextKSubset,
  3270. NextPartition,
  3271. NextPermutation,
  3272. NextSubset,
  3273. NextTableau,
  3274. NormalizeVertices,
  3275. NthPair,
  3276. NthPermutation,
  3277. NthSubset,
  3278. NumberOfCompositions,
  3279. NumberOfDerangements,
  3280. NumberOfInvolutions,
  3281. NumberOfPartitions,
  3282. NumberOfPermutationsByCycles,
  3283. NumberOfSpanningTrees,
  3284. NumberOfTableaux,
  3285. OrientGraph,
  3286. PartialOrderQ,
  3287. PartitionQ,
  3288. Partitions,
  3289. PathConditionGraph,
  3290. Path,
  3291. PerfectQ,
  3292. PermutationGroupQ,
  3293. PermutationQ,
  3294. Permute,
  3295. PlanarQ,
  3296. PointsAndLines,
  3297. Polya,
  3298. PseudographQ,
  3299. RadialEmbedding,
  3300. Radius,
  3301. RandomComposition,
  3302. RandomGraph,
  3303. RandomHeap,
  3304. RandomKSubset,
  3305. RandomPartition,
  3306. RandomPermutation1,
  3307. RandomPermutation2,
  3308. RandomPermutation,
  3309. RandomSubset,
  3310. RandomTableau,
  3311. RandomTree,
  3312. RandomVertices,
  3313. RankGraph,
  3314. RankPermutation,
  3315. RankSubset,
  3316. RankedEmbedding,
  3317. ReadGraph,
  3318. RealizeDegreeSequence,
  3319. RegularGraph,
  3320. RegularQ,
  3321. RemoveSelfLoops,
  3322. RevealCycles,
  3323. RootedEmbedding,
  3324. RotateVertices,
  3325. Runs,
  3326. SamenessRelation,
  3327. SelectionSort,
  3328. SelfComplementaryQ,
  3329. ShakeGraph,
  3330. ShortestPathSpanningTree,
  3331. ShortestPath,
  3332. ShowGraph,
  3333. ShowLabeledGraph,
  3334. SignaturePermutation,
  3335. SimpleQ,
  3336. Spectrum,
  3337. SpringEmbedding,
  3338. StableMarriage,
  3339. Star,
  3340. StirlingFirst,
  3341. StirlingSecond,
  3342. Strings,
  3343. StronglyConnectedComponents,
  3344. Subsets,
  3345. TableauClasses,
  3346. TableauQ,
  3347. TableauxToPermutation,
  3348. Tableaux,
  3349. ToAdjacencyLists,
  3350. ToCycles,
  3351. ToInversionVector,
  3352. ToOrderedPairs,
  3353. ToUnorderedPairs,
  3354. TopologicalSort,
  3355. TransitiveClosure,
  3356. TransitiveQ,
  3357. TransitiveReduction,
  3358. TranslateVertices,
  3359. TransposePartition,
  3360. TransposeTableau,
  3361. TravelingSalesmanBounds,
  3362. TravelingSalesman,
  3363. TreeQ,
  3364. TriangleInequalityQ,
  3365. Turan,
  3366. TwoColoring,
  3367. UndirectedQ,
  3368. UnionSet,
  3369. UnweightedQ,
  3370. V,
  3371. VertexColoring,
  3372. VertexConnectivity,
  3373. VertexCoverQ,
  3374. Vertices,
  3375. WeaklyConnectedComponents,
  3376. Wheel,
  3377. WriteGraph,
  3378. DilworthGraph ]
  3379.  
  3380. EndPackage[ ]
  3381.  
  3382.