fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int main() {
  7. int n;
  8. if (!(cin >> n)) return 0; // Safe check for input
  9.  
  10. vector<int> arr(n);
  11. for (int i = 0; i < n; i++) {
  12. cin >> arr[i];
  13. }
  14.  
  15. int k;
  16. cin >> k;
  17.  
  18. // Use a vector of pairs for cleaner syntax and better performance
  19. vector<pair<int, int>> ans;
  20.  
  21. for (int i = 0; i < n; i++) {
  22. // j <= i + k already guarantees the distance is <= k
  23. for (int j = i + 1; j < n && j <= i + k; j++) {
  24. if (arr[i] == arr[j]) {
  25. cout << "Yes we found the valid pair" << endl;
  26. ans.push_back({i, j});
  27. }
  28. }
  29. }
  30.  
  31. // Printing out the discovered pairs
  32. for (const auto& p : ans) {
  33. cout << p.first << " : " << p.second << endl;
  34. }
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 5324KB
stdin
5
1
2
1
3
3
2
stdout
Yes we found the valid pair
Yes we found the valid pair
0 : 2
3 : 4