Advertisement
Josif_tepe

Untitled

Feb 16th, 2025
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <cmath>
  4. #include <vector>
  5.  
  6. using namespace std;
  7. const int maxn = 1e5 + 10;
  8.  
  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.    
  17.     bool operator < (const node & tmp) const {
  18.         return shortest_path > tmp.shortest_path;
  19.     }
  20. };
  21. int main(){
  22.     int n, V;
  23.     cin >> n >> V;
  24.    
  25.     vector<int> portals(n);
  26.     for(int i = 0; i < n; i++) {
  27.         cin >> portals[i];
  28.     }
  29.    
  30.     vector<pair<int, int>> graph[maxn];
  31.    
  32.     for(int i = 0; i < n; i++) {
  33.         if(i + 1 < n) {
  34.             graph[i].push_back(make_pair(i + 1, 1));
  35.         }
  36.         if(i - 1 >= 0) {
  37.             graph[i].push_back(make_pair(i - 1, 1));
  38.         }
  39.        
  40.         for(int j = 0; j < n; j++) {
  41.             if(portals[i] == portals[j]) {
  42.                 graph[i].push_back(make_pair(j, V));
  43.             }
  44.         }
  45.     }
  46.    
  47.     vector<bool> visited(n, false);
  48.     vector<int> dist(n, 2e9);
  49.    
  50.     priority_queue<node> pq;
  51.     pq.push(node(0, 0));
  52.    
  53.     while(!pq.empty()) {
  54.         node c = pq.top();
  55.         pq.pop();
  56.        
  57.         if(visited[c.idx]) {
  58.             continue;
  59.         }
  60.         visited[c.idx] = true;
  61.        
  62.         for(int i = 0; i < (int) graph[c.idx].size(); i++) {
  63.             int neighbour = graph[c.idx][i].first;
  64.             int weight = graph[c.idx][i].second;
  65.            
  66.             if(!visited[neighbour] and c.shortest_path + weight < dist[neighbour]) {
  67.                 dist[neighbour] = c.shortest_path + weight;
  68.                 pq.push(node(neighbour, dist[neighbour]));
  69.             }
  70.         }
  71.     }
  72.    
  73.     cout << dist[n - 1] << endl;
  74.    
  75.     return 0;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement