题目大意:给出N个数字,在给出M个数字作为要求,M个数字中的每一个数字要求从N个数字中找到两个数字的和和它最接近,并输出来
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 1000000;
int sum[maxn];
int num[maxn];
int main() {
int n;
int mark = 1;
while(scanf("%d", &n) && n) {
printf("Case %d:\n",mark++);
for(int i = 0; i < n; i++)
scanf("%d",&num[i]);
int count = 0;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
sum[count++] = num[i] + num[j];
sort(sum,sum+count);
int m, temp, j, t;
scanf("%d",&m);
for(int i = 0; i < m; i++) {
scanf("%d",&temp);
int min = abs(sum[0] - temp);
for(j = 1; j < count; j++) {
t = abs(sum[j] - temp);
if(t < min)
min = t;
else if (t == min) {
continue;
}else{
printf("Closest sum to %d is %d.\n",temp,sum[j-1]);
break;
}
}
if(j == count)
printf("Closest sum to %d is %d.\n",temp,sum[count-1]);
}
}
return 0;
}