题意:n个数中,找到所给数与其中任意两个不同数字的和的差最小的一个,并输出这个这两个数字的和。
题解:直接将所有不同的数字的和都存起来,然后遍历找到差最小的输出。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 1000000;
int main() {
int n, num[N], m, que, t = 1, vis[N];
while (scanf("%d", &n) && n) {
printf("Case %d:\n", t++);
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; i++)
scanf("%d", &num[i]);
int temp = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
vis[temp++] = num[i] + num[j];
scanf("%d", &m);
for (int i = 1; i <= m; i++) {
scanf("%d", &que);
int temp1 = 0x3f3f3f3f, ans;
for (int j = 0; j < temp; j++)
if (fabs(vis[j] - que) < temp1) {
temp1 = fabs(vis[j] - que);
ans = vis[j];
}
printf("Closest sum to %d is %d.\n", que, ans);
}
}
return 0;
}