Fastrail08

Minimum Multiplications to reach End

Aug 24th, 2025
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int MOD = 1e5;
  5.  
  6. int djikstra(int start, int end, vector<int> &arr){
  7.     priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
  8.     vector<int> distance(1e5, INT_MAX);
  9.    
  10.     //push start in pq and init distance
  11.     pq.emplace(0, start);
  12.     distance[start] = 0;
  13.    
  14.     while(!pq.empty()){
  15.         pair<int, int> top = pq.top();
  16.         pq.pop();
  17.        
  18.         int node = top.second, nodeDist = top.first;
  19.        
  20.         if(distance[node] < nodeDist){
  21.             continue;
  22.         }
  23.        
  24.         for(int i = 0; i < arr.size(); i++){
  25.             int child = ((node % MOD) * arr[i]) % MOD, childDist = nodeDist + 1;
  26.             if(childDist < distance[child]){
  27.                 pq.emplace(childDist, child);
  28.                 distance[child] = childDist;
  29.             }
  30.         }
  31.         //Early Breakage - The first occurence of end popped from pq, is at the shortest distance
  32.         if(node == end){
  33.             return nodeDist;
  34.         }
  35.     }
  36.     return distance[end] == INT_MAX ? -1 : distance[end];
  37. }
  38.  
  39. int minimumMultiplications(vector<int> &arr, int start, int end){
  40.     return djikstra(start, end, arr);
  41. }
  42.  
  43. int main() {
  44.     // your code goes here
  45.     int n, start, end;
  46.     cin >> n;
  47.     vector<int> arr(n);
  48.     for(int i = 0; i < n; i++){
  49.         cin >> arr[i];
  50.     }
  51.     cin >> start >> end;
  52.     cout << minimumMultiplications(arr, start, end) << '\n';
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment