题意:找出数组中和最接近所要求的数的和,先求出所有可能的和,然后本来我是先排序,然后从小到大去找的,直到出现拐点,然后看了学长的二分,就果断用二分了
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> using namespace std; const int MAXN = 1010; int n,m,len; int num_n[MAXN],num_m[MAXN]; int sum[1000010]; void Search(int a) { int left , right , mid , ans; left = 0 , right = len-1; while(1) { if(right-left == 1) { ans = (sum[right]-a)<(a-sum[left])?sum[right]:sum[left]; break; } mid = (left+right)/2; if(sum[mid] > a) right = mid; if(sum[mid] < a) left = mid; if(sum[mid] == a) { ans = a ; break; } } printf("Closest sum to %d is %d.\n" ,a,ans); } void solve() { int i,j,k; for (i = 0,k = 0; i < n; i++) for (j = i + 1; j < n; j++) sum[k++] = num_n[i] + num_n[j]; len = k; sort(sum,sum+k); for (i = 0; i < m; i++) Search(num_m[i]); } int main() { int cas = 1; while (scanf("%d%*c",&n) && n) { for (int i = 0; i < n; i++) scanf("%d%*c",&num_n[i]); scanf("%d%*c",&m); for (int i = 0; i < m; i++) scanf("%d%*c",&num_m[i]); printf("Case %d:\n" ,cas++); solve(); } }