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;}