Advertisement
1nikitas

Untitled

Oct 6th, 2021
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace problemECSharp
  5. {
  6. public class Program
  7. {
  8. static int infinity = 1000000000;
  9.  
  10. public static void Main(string[] args)
  11. {
  12. int n = int.Parse(Console.ReadLine());
  13. int[,] matrix = new int[n, n];
  14. string[] Line;
  15. for (int i = 0; i < n; i++)
  16. {
  17. Line = Console.ReadLine().Split(' ');
  18. for (int j = 0; j < n; j++)
  19. {
  20. matrix[i, j] = int.Parse(Line[j]);
  21. }
  22. }
  23. int[] lengths = new int[n];
  24. for (int i = 0; i < n; i++)
  25. {
  26. lengths[i] = infinity;
  27. }
  28. lengths[0] = 0;
  29. int[] predecessor = new int[n];
  30. for (int k = 0; k < n; k++)
  31. {
  32. for (int i = 0; i < n; i++)
  33. {
  34. for (int j = 0; j < n; j++)
  35. {
  36. if (lengths[j] > lengths[i] + matrix[i, j])
  37. {
  38. lengths[j] = lengths[i] + matrix[i, j];
  39. predecessor[j] = i;
  40. }
  41. }
  42. }
  43. }
  44.  
  45. int firstVertexInCycle = int.MaxValue;
  46. bool hasCycle = false;
  47. for (int i = 0; i < n; i++)
  48. {
  49. for (int j = 0; j < n; j++)
  50. {
  51. /*Cycle is found*/
  52. if (lengths[j] > lengths[i] + matrix[i, j])
  53. {
  54. firstVertexInCycle = j;
  55. hasCycle = true;
  56. break;
  57. }
  58. }
  59. }
  60.  
  61. if (hasCycle)
  62. {
  63. List<int> cycle = new List<int>();
  64. for (int i = 0; i < n - 1; i++)
  65. {
  66. firstVertexInCycle = predecessor[firstVertexInCycle];
  67. }
  68. cycle.Add(firstVertexInCycle);
  69. for (int v = predecessor[firstVertexInCycle]; v != firstVertexInCycle; v = predecessor[v])
  70. {
  71. cycle.Insert(0,v);
  72. }
  73. cycle.Insert(0,firstVertexInCycle);
  74. Console.WriteLine("YES");
  75. Console.WriteLine(cycle.Count);
  76. foreach (var vertex in cycle)
  77. {
  78. Console.Write((vertex + 1) + " ");
  79. }
  80. }
  81. else
  82. {
  83. Console.WriteLine("NO");
  84. }
  85. }
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement