Divide and conquer algorithm - two elements and (merge sort + binary search)

1. Problem description

two elements and
Time Limit: 1000 MS Memory Limit: 5000 KB

Description

Given a collection of N(N<=50000) integers of type int and an integer X of type int, ask whether the sum of two elements in the collection is equal to X.

Input

Input M in the first line indicates that there are M groups of tests. Each group of tests first inputs N and X, and then inputs N integers of type int.

Output

If the sum of two elements is equal to X, output yes, otherwise output no.

Sample Input

2
8 7 
1 5 11 5 4 3 9 6
8 7 
1 5 11 5 5 3 9 5

Sample Output

yes
no

2. Problem analysis

1. Most people’s first reaction may be to solve violently, that is, to query one by one, but the time complexity of this idea is n square; when there are many things in the array, the query time increases exponentially, and this method is no longer applicable;

2. If the array is ordered, the search efficiency will be greatly improved, such as binary search, the time complexity is O(logn), and the worst case is only O(n); while the sorting algorithm time complexity is O(nlogn) ), so the overall complexity is only O(nlogn), so we can sort the array first, then search

3. Code example

#include <iostream>
#include <algorithm>

using namespace std;

const int MAXN = 50005;

int arr[MAXN];

bool has_pair_with_sum(int arr[], int n, int X) {
    // 先对整个数组进行快速排序
    sort(arr, arr + n);
    // 对于每个元素
    for (int i = 0; i < n; i++) {
        // 使用二分查找来查找 X 减去该元素的值是否在数组中出现过
        int j = lower_bound(arr + i + 1, arr + n, X - arr[i]) - arr;
        // 如果出现过,则说明存在两个元素的和等于 X
        if (j < n && arr[j] == X - arr[i]) {
            return true;
        }
    }
    // 如果不存在两个元素的和等于 X,则返回 false
    return false;
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, X;
        cin >> n >> X;
        for (int i = 0; i < n; i++) {
            cin >> arr[i];
        }
        if (has_pair_with_sum(arr, n, X)) {
            cout << "yes" << endl;
        } else {
            cout << "no" << endl;
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/lyhizjj/article/details/130627756