Написать на C++:даны два массива. Определить существуют ли в первом массиве такие два элемента, что их сумма равна сумме каких-либо трёх элементов второго массива
#include <iostream> #include <unordered_set> bool checkArrays(int arr1[], int n1, int arr2[], int n2) { std::unordered_set<int> sumSet; for(int i = 0; i < n2-1; i++) { for(int j = i+1; j < n2; j++) { sumSet.insert(arr2[i] + arr2[j]); } } for(int i = 0; i < n1-1; i++) { for(int j = i+1; j < n1; j++) { if(sumSet.find(arr1[i] + arr1[j]) != sumSet.end()) { return true; } } } return false; } int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {2, 4, 6, 8, 10}; int n1 = sizeof(arr1)/sizeof(arr1[0]); int n2 = sizeof(arr2)/sizeof(arr2[0]); if (checkArrays(arr1, n1, arr2, n2)) { std::cout << "Such two elements exist in the first array that their sum is equal to the sum of any three elements in the second array" << std::endl; } else { std::cout << "Such two elements do not exist in the first array that their sum is equal to the sum of any three elements in the second array" << std::endl; } return 0; }
Пример работы программы:
Such two elements exist in the first array that their sum is equal to the sum of any three elements in the second array
#include <unordered_set>
bool checkArrays(int arr1[], int n1, int arr2[], int n2) {
std::unordered_set<int> sumSet;
for(int i = 0; i < n2-1; i++) {
for(int j = i+1; j < n2; j++) {
sumSet.insert(arr2[i] + arr2[j]);
}
}
for(int i = 0; i < n1-1; i++) {
for(int j = i+1; j < n1; j++) {
if(sumSet.find(arr1[i] + arr1[j]) != sumSet.end()) {
return true;
}
}
}
return false;
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {2, 4, 6, 8, 10};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int n2 = sizeof(arr2)/sizeof(arr2[0]);
if (checkArrays(arr1, n1, arr2, n2)) {
std::cout << "Such two elements exist in the first array that their sum is equal to the sum of any three elements in the second array" << std::endl;
} else {
std::cout << "Such two elements do not exist in the first array that their sum is equal to the sum of any three elements in the second array" << std::endl;
}
return 0;
}
Пример работы программы:
Such two elements exist in the first array that their sum is equal to the sum of any three elements in the second array