fork download
  1. /*******************************************************
  2. 5) GFG — Nearest Left Index That Divides Current Element
  3.  
  4. Problem:
  5. For each i, find nearest j<i such that A[i] % A[j] == 0, else -1.
  6.  
  7. Idea:
  8. - For x=A[i], enumerate all divisors d of x.
  9. - If we saw d earlier at lastIndex[d], then that's a valid j.
  10. - Take maximum j among all divisors -> nearest to left.
  11.  
  12. Time: O(n * sqrt(maxA)) expected
  13. *******************************************************/
  14.  
  15. #include <bits/stdc++.h> // standard CP header
  16. using namespace std; // use std names directly
  17.  
  18. int main() { // program start
  19. ios::sync_with_stdio(false); // fast I/O
  20. cin.tie(nullptr); // fast I/O
  21.  
  22. int n; // array size
  23. cin >> n; // read n
  24. vector<int> A(n); // array
  25. for (int i = 0; i < n; i++) cin >> A[i]; // read elements
  26.  
  27. unordered_map<int,int> lastIndex; // lastIndex[value] = most recent index where value appeared
  28. lastIndex.reserve((size_t)n * 2); // reserve to reduce rehashing (performance trick)
  29.  
  30. for (int i = 0; i < n; i++) { // process from left to right
  31. int x = A[i]; // current value
  32. int best = -1; // best answer (nearest index), -1 if none
  33.  
  34. for (int d = 1; 1LL * d * d <= x; d++) { // enumerate divisors up to sqrt(x)
  35. if (x % d) continue; // if d is not a divisor, skip
  36.  
  37. int d1 = d; // first divisor
  38. int d2 = x / d; // paired divisor
  39.  
  40. auto it1 = lastIndex.find(d1); // see if d1 was seen
  41. if (it1 != lastIndex.end()) best = max(best, it1->second); // update nearest index
  42.  
  43. auto it2 = lastIndex.find(d2); // see if d2 was seen
  44. if (it2 != lastIndex.end()) best = max(best, it2->second); // update nearest index
  45. }
  46.  
  47. cout << best << (i + 1 == n ? '\n' : ' '); // print answer (0-based index)
  48.  
  49. lastIndex[x] = i; // update last seen index for x
  50. }
  51.  
  52. return 0; // done
  53. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Standard output is empty