fork download
  1. #include <iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. using ll = long long;
  5. #define fo(i,start,end) for(int i=start;i<end;i++)
  6.  
  7. vector<pair<int,int>> FindOptimalPairs(vector<int>&arr,int k){
  8. vector<pair<int,int>>result;
  9. // arrr = {1,5,3,4,2}, k = 2
  10. unordered_map<int,int>mp; //element -> index
  11. fo(j,0,5){
  12. int a1 = k + arr[j]; // 2 + 3 = 5
  13. int a2 = arr[j] - k; // 3 - 2 = 1
  14. if(mp.find(a1) != mp.end()){
  15. result.push_back({mp[a1],j});
  16. }
  17. if(mp.find(a2) != mp.end()){
  18. result.push_back({mp[a2],j});
  19. }
  20. mp[arr[j]] = j;
  21. }
  22. //for loop ends here
  23. return result;
  24. }
  25.  
  26.  
  27. int main() {
  28. // your code goes here
  29. vector<int>arr = {1,5,3,4,2};
  30. ll k = 2;
  31. vector<pair<int,int>>ans = FindOptimalPairs(arr,k);
  32. cout<<"Pairs are:"<<endl;
  33. for(pair<int,int>& it:ans){
  34. int fp = it.first;
  35. int sp = it.second;
  36. cout<<"{"<<fp+1<<","<<sp+1<<"},"<<endl; //one based indexing
  37. }
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Pairs are:
{2,3},
{1,3},
{4,5},