home *** CD-ROM | disk | FTP | other *** search
/ Math Solutions 1995 October / Math_Solutions_CD-ROM_Walnut_Creek_October_1995.iso / pc / mac / discrete / combinat.m
Encoding:
Text File  |  1995-06-22  |  98.8 KB  |  3,711 lines

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