Pr.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Pruf
  7. {
  8. internal class Pr
  9. {
  10. List<List<int>> graph;
  11. List<int> codePreufer;
  12. public Pr(List<List<int>> graph)
  13. {
  14. this.graph = graph;
  15. codePreufer = new List<int>();
  16. }
  17. bool SearchLeaf(int leaf)
  18. {
  19. int counter=0;
  20. for (int i = 0; i < graph.Count; i++)
  21. {
  22. for (int j = 0; j < graph[i].Count; j++)
  23. {
  24. if (leaf == graph[i][j])
  25. counter++;
  26. }
  27. }
  28. if (counter > 1)
  29. return false;
  30. else
  31. return true;
  32. }
  33. public void RealizationAlg()
  34. {
  35. while (true)
  36. {
  37. int minLeaf = int.MaxValue;
  38. int indexRow = int.MaxValue;
  39. int indexCol = int.MaxValue;
  40. if (graph.Count == 1)
  41. break;
  42. List<List<int>> leaves = new List<List<int>>();
  43. for (int i = 0; i < graph.Count; i++)
  44. {
  45. for (int j = 0; j < graph[i].Count; j++)
  46. {
  47. List<int> leafAndIndexes = new List<int>();
  48. if (SearchLeaf(graph[i][j]))
  49. {
  50. leafAndIndexes.Add(graph[i][j]);
  51. leafAndIndexes.Add(i);
  52. leafAndIndexes.Add(j);
  53. leaves.Add(leafAndIndexes);
  54. }
  55. }
  56. }
  57. for (int i = 0; i < leaves.Count; i++)
  58. {
  59. if (minLeaf > leaves[i][0])
  60. {
  61. minLeaf = leaves[i][0];
  62. indexRow = leaves[i][1];
  63. indexCol = leaves[i][2];
  64. }
  65. }
  66. if (indexCol == 0)
  67. {
  68. codePreufer.Add(graph[indexRow][1]);
  69. graph.RemoveAt(indexRow);
  70. }
  71. else
  72. {
  73. codePreufer.Add(graph[indexRow][0]);
  74. graph.RemoveAt(indexRow);
  75. }
  76. }
  77. }
  78. public override string ToString() => string.Join(" ", codePreufer);
  79. }
  80. }