Advertisement
Guest User

Dijkstra

a guest
Jun 18th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. // Dijkstra.cpp: определяет точку входа для консольного приложения.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. int main()
  10. {
  11.     setlocale(0, "");
  12.     int C[10][10];
  13.     int n, m;
  14.     int x, y, c;
  15.     cout << "Введите кол-во вершин ";
  16.     cin >> n;
  17.     cout << endl;
  18.     cout << "Введите кол-во ребер ";
  19.     cin >> m;
  20.     cout << endl;
  21.     for (int i = 1; i <= n; i++)
  22.         for (int j = 1; j <= n; j++)
  23.             C[i][j] = 100;
  24.  
  25.     for (int i = 1; i <= m; i++) {
  26.         cout << "Введите откуда ребро, куда ребро, вес ребра " << endl;
  27.         cin >> x >> y >> c;
  28.         C[x][y] = c;
  29.     }
  30.  
  31.     for (int i = 1; i <= n; i++) {
  32.         cout << endl;
  33.         for (int j = 1; j <= n; j++) {
  34.             cout << " " << C[i][j];
  35.         }
  36.     }
  37.     cout << endl;
  38.  
  39.     int S[10];
  40.     int D[10];
  41.     for (int i = 1; i <= n; i++) {
  42.         S[i] = 0;
  43.         D[i] = C[1][i];
  44.     }
  45.     S[1] = 1; int min, w;
  46.     //
  47.     for (int i = 1; i <= n-1; i++) {
  48.  
  49.         min = 100;
  50.         for (int j = 2; j <= n; j++) {
  51.  
  52.             if ((S[j] == 0) && (D[j] < min)) {
  53.                 min = D[j];
  54.                 w = j;
  55.             }
  56.         }
  57.  
  58.         S[w] = 1;
  59.  
  60.         for (int j = 2; j <= n; j++) {
  61.             if ((D[j] > D[w] + C[w][j]) && (S[j] == 0)) {
  62.                 D[j] = D[w] + C[w][j];
  63.             }
  64.         }
  65.     }
  66.     for (int i = 2; i <= n; i++) {
  67.         cout << "k " << i << "-й вершине путь " << D[i] << endl;
  68.     }
  69.  
  70.  
  71.  
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement