#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int N = 1005;
const int INF = 0x3f3f3f3f;
int set[N];
int query[N];
int n,m;
int solve(int num) { //二分查找最近的和
int left = 0,right = n-1;
int sum,dis;
int min = INF,ans;
while(left < right) {
sum = set[left] + set[right];
dis = abs(sum - num);
if(dis < min) {
min = dis;
ans = sum;
}
if(sum == num) {
return num;
}else if(sum < num) {
left++;
}else {
right--;
}
}
return ans;
}
int main() {
int cas = 1;
while(scanf("%d",&n) != EOF && n) {
for(int i = 0; i < n; i++) {
scanf("%d",&set[i]);
}
sort(set,set+n);
scanf("%d",&m);
for(int i = 0; i < m; i++) {
scanf("%d",&query[i]);
}
printf("Case %d:\n",cas++);
for(int i = 0; i < m; i++) {
int ans = solve(query[i]);
printf("Closest sum to %d is %d.\n",query[i],ans);
}
}
return 0;
}
uva 10487
最新推荐文章于 2020-09-26 18:54:00 发布