Advertisement
allia

алгоритм Прима

Jan 5th, 2021
865
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. const int INF = 1000000;
  5.  
  6. class Graph
  7. {
  8.   private:
  9.   bool orient;
  10.   int n, **arr, shet_reber, **min_ost;
  11.  
  12.   public:
  13.   Graph (int **matrix, int x, int shet)
  14.   {
  15.     n = x;
  16.     arr = matrix;
  17.     shet_reber = shet;
  18.   }
  19.  
  20.  void get_span_tree();
  21.  void add_edge(int a, int b);
  22.  void init_min_ost();
  23.  void get_min_ost();
  24. };
  25.  
  26. void Graph::get_min_ost()
  27. {
  28.   int path_length = 0;
  29.  
  30.   for (int i =0; i < n; i++)
  31.    for (int j = i; j < n; j++)
  32.    path_length += min_ost[i][j];
  33.  
  34.   cout << path_length << endl;
  35.  
  36.    for (int i = 0; i < n; i++)
  37.     {
  38.       for (int j = 0; j < n; j++)
  39.       {
  40.         cout.width(3);
  41.         cout << min_ost[i][j] << " ";
  42.       }
  43.      cout << endl;
  44.     }
  45. }
  46.  
  47. void Graph::init_min_ost()
  48. {
  49.   min_ost = new int*[n];
  50.  
  51.   for (int i =0; i < n; i++)
  52.    min_ost[i] = new int[n];
  53.  
  54.   for (int i = 0; i < n; i++)
  55.    for (int j = 0; j < n; j++)
  56.     min_ost[i][j] = 0;
  57. }
  58.  
  59. void Graph::add_edge(int a, int b)
  60. {
  61.   min_ost[a][b] = arr[a][b];
  62.   min_ost[b][a] = min_ost[a][b];
  63. }
  64.  
  65. void Graph::get_span_tree()
  66. {
  67.   init_min_ost();
  68.   int wmin;
  69.   int i, j, znach, *B = new int[n];
  70.   B[0] = -1;
  71.  
  72.   for (i = 1; i < n; i++)
  73.     B[i] = 0;
  74.  
  75.   for (i = 1; i < n; i++)
  76.    {
  77.     wmin = INF;
  78.     znach = 0;
  79.     for (j = 1; j < n; j++)
  80.       if (B[j] != -1 && wmin > arr[j][B[j]])
  81.       {
  82.         znach = j;
  83.         wmin = arr[j][B[j]];
  84.       }
  85.  
  86.       if (!znach)
  87.        return;
  88.  
  89.       add_edge(znach, B[znach]);
  90.       B[znach] = -1;
  91.  
  92.       for (j = 1; j < n; j++)
  93.       if (B[j] != -1 && arr[j][B[j]] > arr[j][znach])
  94.         B[j] = znach;
  95.   }
  96.   get_min_ost();
  97. }
  98.  
  99.  
  100. int main()
  101. {
  102.  int n, shet_reber = 0;
  103.  cin >> n;
  104.  
  105. int **arr = new int*[n];
  106.  
  107. for ( int i = 0; i < n; i++)
  108.      arr[i] = new int[n];
  109.    
  110. for (int i =0; i < n; i++)
  111.   for (int j =0; j < n; j++)  
  112.      {
  113.        cin >> arr[i][j];
  114.         if (arr[i][j] == 0)
  115.          arr[i][j] = INF;
  116.         else shet_reber++;
  117.      }
  118.  
  119.  shet_reber /= 2;
  120.  Graph object(arr, n, shet_reber);
  121.  object.get_span_tree();
  122. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement