Advertisement
Josif_tepe

Untitled

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