Advertisement
coloriot

HA45

Mar 12th, 2025
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4. using namespace std;
  5.  
  6. class PairFinder {
  7. private:
  8.     vector<int> arr;
  9.     int target;
  10.     pair<int, int> indices;
  11.     bool found;
  12.  
  13. public:
  14.     PairFinder() : target(0), found(false) {}
  15.  
  16.     void input() {
  17.         int n;
  18.         cout << "Введите количество элементов и число k: ";
  19.         cin >> n >> target;
  20.         arr.resize(n);
  21.         cout << "Введите элементы: ";
  22.         for (int i = 0; i < n; i++) {
  23.             cin >> arr[i];
  24.         }
  25.     }
  26.  
  27.     // Функция поиска пары индексов
  28.     bool findPair() {
  29.         unordered_map<int, int> hash;
  30.         for (int i = 0; i < arr.size(); i++) {
  31.             int complement = target - arr[i];
  32.             if (hash.find(complement) != hash.end()) {
  33.                 indices = make_pair(hash[complement], i);
  34.                 found = true;
  35.                 return true;
  36.             }
  37.             hash[arr[i]] = i;
  38.         }
  39.         return false;
  40.     }
  41.  
  42.     void output() const {
  43.         if (found) {
  44.             cout << "Найденные индексы: " << indices.first << " и " << indices.second << endl;
  45.         } else {
  46.             cout << "Пара, удовлетворяющая условию, не найдена." << endl;
  47.         }
  48.     }
  49. };
  50.  
  51. int main() {
  52.     PairFinder pf;
  53.     pf.input();
  54.     pf.findPair();
  55.     pf.output();
  56.     return 0;
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement