Advertisement
Josif_tepe

Untitled

Feb 8th, 2025
29
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 <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.     for(int i = 0; i < n; i++) {
  30.         if(i - 1 >= 0) {
  31.             graph[i].push_back(make_pair(i - 1, 1));
  32.         }
  33.         if(i + 1 < n) {
  34.             graph[i].push_back(make_pair(i + 1, 1));
  35.         }
  36.        
  37.         for(int j = 0; j < n; j++) {
  38.             if(portal[i] == portal[j]) {
  39.                 graph[i].push_back(make_pair(j, v));
  40.             }
  41.         }
  42.     }
  43.    
  44.     vector<bool> visited(n, false);
  45.     vector<int> dist(n, INF);
  46.     priority_queue<node> pq;
  47.     pq.push(node(0, 0));
  48.     dist[0] = 0;
  49.     while(!pq.empty()) {
  50.         node c = pq.top();
  51.         pq.pop();
  52.        
  53.         if(visited[c.idx]) {
  54.             continue;
  55.         }
  56.         visited[c.idx] = true;
  57.        
  58.         for(int i = 0; i < (int) graph[c.idx].size(); i++) {
  59.             int neighbour = graph[c.idx][i].first;
  60.             int weight = graph[c.idx][i].second;
  61.            
  62.             if(!visited[neighbour] and c.shortest_path + weight < dist[neighbour]) {
  63.                 dist[neighbour] = c.shortest_path + weight;
  64.                 pq.push(node(neighbour, dist[neighbour]));
  65.             }
  66.         }
  67.     }
  68.     cout << dist[n - 1] << endl;
  69.    
  70.     return 0;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement