Advertisement
Josif_tepe

Untitled

Apr 14th, 2025
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5. struct node {
  6.     int idx, shortest_path;
  7.     node() {}
  8.     node(int _idx, int _shortest_path) {
  9.         idx = _idx;
  10.         shortest_path = _shortest_path;
  11.     }
  12.    
  13.     bool operator < (const node & tmp) const {
  14.         return shortest_path > tmp.shortest_path;
  15.     }
  16. };
  17.  
  18. int main() {
  19.     int n, V;
  20.     cin >> n >> V;
  21.    
  22.     vector<int> portals(n);
  23.     for(int i = 0; i < n; i++) {
  24.         cin >> portals[i];
  25.     }
  26.     priority_queue<node> pq;
  27.     pq.push(node(0, 0));
  28.     vector<bool> visited(n, false);
  29.     vector<bool> portal_visited(11, false);
  30.    
  31.     while(!pq.empty()) {
  32.         node current_node = pq.top();
  33.         pq.pop();
  34.        
  35.         if(current_node.idx == n - 1) {
  36.             cout << current_node.shortest_path << endl;
  37.             return 0;
  38.         }
  39.         if(visited[current_node.idx]) {
  40.             continue;
  41.         }
  42.         visited[current_node.idx] = true;
  43.        
  44.         if(current_node.idx + 1 < n) {
  45.             pq.push(node(current_node.idx + 1, current_node.shortest_path + 1));
  46.         }
  47.         if(current_node.idx - 1 >= 0) {
  48.             pq.push(node(current_node.idx - 1, current_node.shortest_path + 1));
  49.         }
  50.        
  51.         if(!portal_visited[portals[current_node.idx]]) {
  52.             for(int i = 0; i < n; i++) {
  53.                 if(portals[i] == portals[current_node.idx]) {
  54.                     pq.push(node(i, current_node.shortest_path + V));
  55.                 }
  56.             }
  57.             portal_visited[portals[current_node.idx]] = true;
  58.         }
  59.     }
  60.    
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement