Infiniti_Inter

стоки

May 26th, 2020
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.54 KB | None | 0 0
  1.  
  2.  
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. namespace ConsoleApp5
  8. {
  9.     public class Queue
  10.     {
  11.         private class Node //вложенный класс, реализующий базовый элемент очереди
  12.         {
  13.             private object inf;
  14.             private Node next;
  15.             public Node(object nodeInfo)
  16.             {
  17.                 inf = nodeInfo;
  18.                 next = null;
  19.             }
  20.             public Node Next
  21.             {
  22.                 get { return next; }
  23.                 set { next = value; }
  24.             }
  25.             public object Inf
  26.             {
  27.                 get { return inf; }
  28.                 set { inf = value; }
  29.             }
  30.         } //конец класса Node
  31.         private Node head;
  32.         private Node tail;
  33.         public Queue()
  34.         {
  35.             head = null;
  36.             tail = null;
  37.         }
  38.         public void Add(object nodeInfo)
  39.         {
  40.             Node r = new Node(nodeInfo);
  41.             if (head == null)
  42.             {
  43.                 head = r;
  44.                 tail = r;
  45.             }
  46.             else
  47.             {
  48.                 tail.Next = r;
  49.                 tail = r;
  50.             }
  51.         }
  52.         public object Take()
  53.         {
  54.             if (head == null)
  55.             {
  56.                 throw new Exception("Очередь пуста.");
  57.             }
  58.             else
  59.             {
  60.                 Node r = head;
  61.                 head = head.Next;
  62.                 if (head == null)
  63.                 {
  64.                     tail = null;
  65.                 }
  66.                 return r.Inf;
  67.             }
  68.         }
  69.         public bool IsEmpty
  70.         {
  71.             get
  72.             {
  73.                 if (head == null)
  74.                 {
  75.                     return true;
  76.                 }
  77.                 else
  78.                 {
  79.                     return false;
  80.                 }
  81.             }
  82.         }
  83.     }
  84.     public class Graph
  85.     {
  86.         private class Node //вложенный класс для скрытия данных и алгоритмов
  87.         {
  88.             private int[,] array; //матрица смежности
  89.             public int this[int i, int j] //индексатор для обращения к матрице смежности
  90.             {
  91.                 get
  92.                 {
  93.                     return array[i, j];
  94.                 }
  95.                 set
  96.                 {
  97.                     array[i, j] = value;
  98.                 }
  99.             }
  100.             public int Size //свойство для получения размерности матрицы смежности
  101.             {
  102.                 get
  103.                 {
  104.                     return array.GetLength(0);
  105.                 }
  106.             }
  107.             private bool[] nov; //вспомогательный массив: если i-ый элемент массива равен
  108.                                 //true, то i-ая вершина еще не просмотрена; если i-ый
  109.                                 //элемент равен false, то i-ая вершина просмотрена
  110.             public void NovSet() //метод помечает все вершины графа как непросмотреные
  111.             {
  112.                 for (int i = 0; i < Size; i++)
  113.                 {
  114.                     nov[i] = true;
  115.                 }
  116.             }
  117.             //конструктор вложенного класса, инициализирует матрицу смежности и
  118.             // вспомогательный массив
  119.             public Node(int[,] a)
  120.             {
  121.                 array = a;
  122.                 nov = new bool[a.GetLength(0)];
  123.             }
  124.             public void Solve()
  125.             {
  126.                 int n = array.GetLength(0);
  127.                 List<int> stock = new List<int>();
  128.                 for (int i = 0; i < n; ++i)
  129.                 {
  130.                     int input = 0;
  131.                     for (int j = 0; j < n; ++j)
  132.                         if (this[i, j] != 0)
  133.                             input++;
  134.                     if (input == 0)
  135.                         stock.Add(i + 1);
  136.                 }
  137.                 foreach(var v in stock)
  138.                     Console.Write(v + " ");
  139.                 Console.WriteLine();
  140.             }
  141.             public long[,] Floyd(out int[,] p)
  142.             {
  143.                 int i, j, k;
  144.                 //создаем массивы р и а
  145.                 long[,] a = new long[Size, Size];
  146.                 p = new int[Size, Size];
  147.                 for (i = 0; i < Size; i++)
  148.                 {
  149.                     for (j = 0; j < Size; j++)
  150.                     {
  151.                         if (i == j)
  152.                         {
  153.                             a[i, j] = 0;
  154.                         }
  155.                         else
  156.                         {
  157.                             if (array[i, j] == 0)
  158.                             {
  159.                                 a[i, j] = int.MaxValue;
  160.                             }
  161.                             else
  162.                             {
  163.                                 a[i, j] = array[i, j];
  164.                             }
  165.                         }
  166.                         p[i, j] = -1;
  167.                     }
  168.                 }
  169.                 //осуществляем поиск кратчайших путей
  170.                 for (k = 0; k < Size; k++)
  171.                 {
  172.                     for (i = 0; i < Size; i++)
  173.                     {
  174.                         for (j = 0; j < Size; j++)
  175.                         {
  176.                             long distance = a[i, k] + a[k, j];
  177.                             if (a[i, j] > distance)
  178.                             {
  179.                                 a[i, j] = distance;
  180.                                 p[i, j] = k;
  181.                             }
  182.                         }
  183.                     }
  184.                 }
  185.                 return a;//в качестве результата возвращаем массив кратчайших путей между
  186.             } //всеми парами вершин
  187.               //восстановление пути от вершины a до вершины в для алгоритма Флойда
  188.             public void WayFloyd(int a, int b, int[,] p, ref Queue items)
  189.             {
  190.                 int k = p[a, b];
  191.                 //если k<> -1, то путь состоит более чем из двух вершин а и b, и проходит через
  192.                 //вершину k, поэтому
  193.                 if (k != -1)
  194.                 {
  195.                     // рекурсивно восстанавливаем путь между вершинами а и k
  196.                     WayFloyd(a, k, p, ref items);
  197.                     items.Add(k); //помещаем вершину к в очередь
  198.                                   // рекурсивно восстанавливаем путь между вершинами k и b
  199.                     WayFloyd(k, b, p, ref items);
  200.                 }
  201.             }
  202.         }
  203.  
  204.         //конец вложенного клаcса
  205.  
  206.         private Node graph; //закрытое поле, реализующее АТД «граф»
  207.         public Graph(string name) //конструктор внешнего класса
  208.         {
  209.             using (StreamReader file = new StreamReader(name))
  210.             {
  211.                 int n = int.Parse(file.ReadLine());
  212.                 int[,] a = new int[n, n];
  213.                 for (int i = 0; i < n; i++)
  214.                 {
  215.                     string line = file.ReadLine();
  216.                     string[] mas =
  217.  
  218.                     line.Split(' ');
  219.                     for (int j = 0; j < n; j++)
  220.                     {
  221.                         a[i, j] = int.Parse(mas[j]);
  222.                     }
  223.                 }
  224.                 graph = new Node(a);
  225.             }
  226.         }
  227.         public void Show()
  228.         {
  229.             for (int i = 0; i < graph.Size; i++)
  230.             {
  231.                 for (int j = 0; j < graph.Size; j++)
  232.                 {
  233.                     Console.Write("{0,4}", graph[i, j]);
  234.                 }
  235.                 Console.WriteLine();
  236.             }
  237.         }
  238.         public void Solve()
  239.         {
  240.             graph.Solve();
  241.         }
  242.         public void Resize(string name)
  243.         {
  244.             using (StreamReader file = new StreamReader(name))
  245.             {
  246.                 int n = int.Parse(file.ReadLine());
  247.                 int[,] help = new int[n - 1, n - 1];
  248.                 for (int i = 0; i < n - 1; i++)
  249.                 {
  250.                     for (int j = 0; j < n - 1; j++)
  251.                     {
  252.                         help[i, j] = graph[i, j];
  253.                     }
  254.  
  255.                 }
  256.                 graph = new Node(help);
  257.             }
  258.         }
  259.         public void Floyd(int i, int j)
  260.         {
  261.             int[,] p;
  262.             long[,] a = graph.Floyd(out p); //запускаем алгоритм Флойда
  263.                                             //анализируем полученные данные и выводим их на экран
  264.             if (i != j)
  265.             {
  266.                 if ((a[i, j] == int.MaxValue) || (a[i, j] == -1))
  267.                 {
  268.                     Console.WriteLine("Пути из вершины {0} в вершину {1} не существует", i, j);
  269.                 }
  270.                 else
  271.                 {
  272.                     Console.Write("Кратчайший путь от вершины {0} до вершины {1} равен {2}, ", i, j, a[i, j]);
  273.                     Console.Write(" путь ");
  274.                     Queue items = new Queue();
  275.                     items.Add(i);
  276.                     graph.WayFloyd(i, j, p, ref items);
  277.                     items.Add(j);
  278.                     while (!items.IsEmpty)
  279.                     {
  280.                         Console.Write("{0} ", items.Take());
  281.                     }
  282.                     Console.WriteLine();
  283.                 }
  284.             }
  285.         }
  286.     }
  287.     class Program
  288.     {
  289.         static void Main()
  290.         {
  291.             Graph g = new Graph(@"D:\input.txt");
  292.             Console.WriteLine("Graph:");
  293.             g.Show();
  294.             Console.WriteLine("Стоком(-ами) является(-ются) вершина(-ы) :");
  295.             g.Solve();
  296.            
  297.            
  298.            
  299.         }
  300.     }
  301. }
Add Comment
Please, Sign In to add comment