10487
就是个标准的二分题,查找到应该插入的位置两边哪个数和这个数的差的绝对值最小即可
//============================================================================ // Name : 10487.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> using namespace std; int a[1000010], in[1010]; int l, r, mid, num, n, T, m, t; int main() { T = 0; while(scanf("%d", &n)&&n) { T++; printf("Case %d:\n", T); for(int i = 1;i <= n;i++) { scanf("%d", &in[i]); } num = 1; for(int i = 1;i <= n;i++) { for(int j = i+1;j <= n;j++) { a[num] = in[i]+in[j]; num++; } } num--; sort(a+1, a+num+1); a[0] = a[1]-1; a[num+1] = a[num]+1; //printf("1:%d\n", a[1]); scanf("%d", &m); while(m--) { scanf("%d", &t); printf("Closest sum to %d is ", t); l = 0;r = num+1; while(l+1 != r) { mid = (l+r)/2; if(a[mid] > t) { r = mid; } else { l = mid; } } if(l == 0) printf("%d.\n", a[r]); else if(l == num) printf("%d.\n", a[num]); else printf("%d.\n", abs(t-a[l]) < abs(a[r]-t)?a[l]:a[r]); } } return 0; }