# Sha 10487 closest sums (Binary Search)

Source: Internet
Author: User

Question connection: 10487-closest sums

N numeric values are given, and m numeric values are given. Each numeric value must be found in the first n numeric values, yes, the sum of the two values is the sum of any two values and the sum is the most connected to the query value.

Solution: store the sum of N numbers in an array, sort them in ascending order, and use the binary method to find them. Note that if there are two, the output is the smallest.

`#include <stdio.h>#include <set>#include <vector>#include <algorithm>using namespace std;const int N = 1005;int num[N];vector<int> sum;int main() {    int n, m, v, cas = 1;    vector<int>::iterator it;    while (scanf("%d", &n) == 1 && n) {sum.clear();for (int i = 0; i < n; i++) {    scanf("%d", &num[i]);    for (int j = 0; j < i; j++)sum.push_back(num[i] + num[j]);}sort(sum.begin(), sum.end());scanf("%d", &m);printf("Case %d:\n", cas++);for (int i = 0; i < m; i++) {    scanf("%d", &v);    it = lower_bound(sum.begin(),sum.end(), v);    int Min = *it;    if (it != sum.begin() && abs(*(it - 1) - v) < abs(Min - v))Min = *(it - 1);    printf("Closest sum to %d is %d.\n", v, Min);  }    }    return 0;}`
Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.