Advertisement
coloriot

HA31_Path(8)

Nov 15th, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. const int INF = 1000000000;
  7.  
  8. class Graph {
  9. private:
  10.     int N; // Количество вершин
  11.     vector<vector<int> > adj;
  12.     vector<vector<int> > weights;
  13.     vector<int> dist;
  14.     vector<bool> used;
  15.  
  16. public:
  17.     Graph(int n) {
  18.         N = n;
  19.         adj.resize(N);
  20.         weights.resize(N, vector<int>(N, -1));
  21.         dist.resize(N, INF);
  22.         used.resize(N, false);
  23.     }
  24.  
  25.     void add_edge(int from, int to, int weight) {
  26.         adj[from].push_back(to);
  27.         if (weights[from][to] == -1 || weight < weights[from][to]) {
  28.             weights[from][to] = weight;
  29.         }
  30.     }
  31.  
  32.     int dijkstra(int start_v, int end_v) {
  33.         dist[start_v] = 0;
  34.  
  35.         for (int i = 0; i < N; ++i) {
  36.             int v = -1;
  37.             for (int j = 0; j < N; ++j) {
  38.                 if (!used[j] && (v == -1 || dist[j] < dist[v])) {
  39.                     v = j;
  40.                 }
  41.             }
  42.  
  43.             if (dist[v] == INF) {
  44.                 break;
  45.             }
  46.  
  47.             used[v] = true;
  48.  
  49.             for (size_t j = 0; j < adj[v].size(); ++j) {
  50.                 int to = adj[v][j];
  51.                 int weight = weights[v][to];
  52.  
  53.                 if (dist[v] + weight < dist[to]) {
  54.                     dist[to] = dist[v] + weight;
  55.                 }
  56.             }
  57.         }
  58.  
  59.         if (dist[end_v] == INF) {
  60.             return -1;
  61.         } else {
  62.             return dist[end_v];
  63.         }
  64.     }
  65. };
  66.  
  67. int main() {
  68.     int N, M;
  69.     cin >> N >> M;
  70.  
  71.     int S, F;
  72.     cin >> S >> F;
  73.     S--;
  74.     F--;
  75.  
  76.     Graph graph(N);
  77.  
  78.     for (int i = 0; i < M; ++i) {
  79.         int A, B, T;
  80.         cin >> A >> B >> T;
  81.         A--;
  82.         B--;
  83.         graph.add_edge(A, B, T);
  84.     }
  85.  
  86.     int result = graph.dijkstra(S, F);
  87.     cout << result << endl;
  88.  
  89.     return 0;
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement