Problem D
Closest Sums
Input: standard input
Output: standard output
Time Limit: 3 seconds
Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find a sum of two distinct numbers from the set, which is closest to the query number.
Input
Input contains multiple cases.
Each case starts with an integer n (1<n<=1000), which indicates, how many numbers are in the set of integer. Next n lines contain n numbers. Of course there is only one number in a single line. The next line contains a positive integer m giving the number of queries, 0 < m < 25. The next m lines contain an integer of the query, one per line.
Input is terminated by a case whose n=0. Surely, this case needs no processing.
Output
Output should be organized as in the sample below. For each query output one line giving the query value and the closest sum in the format as in the sample. Inputs will be such that no ties will occur.
Sample input
5
3
12
17
33
34
3
1
51
30
3
1
2
3
3
1
2
3
3
1
2
3
3
4
5
6
0
Sample output
Case 1:
Closest sum to 1 is 15.
Closest sum to 51 is 51.
Closest sum to 30 is 29.
Case 2:
Closest sum to 1 is 3.
Closest sum to 2 is 3.
Closest sum to 3 is 3.
Case 3:
Closest sum to 4 is 4.
Closest sum to 5 is 5.
Closest sum to 6 is 5.
描述:
在一组数中找出与给定数最接近的和(2个数的和)。
分析 :
常见 面试题。与(在数组中查找2个数,他们的和与给定数相等)的做法差不多。
最直接的方法是,把所有的和找出来,与给定的数(设为q)比较。
优化的思路是尽量减少求和和比较的次数。把不需要的操作尽早排除。
1.先把数组排序。
2.第一个数(设为x)和最后一个数(设为y)相加得到和(设为z)
3.若z > q,则x到y之间的数与y相加一定都大于q,且都大于x+y,所以x+y-q是其中最小的, 所以x到y之间的数与y的求和都可以剪除。
4.若z < q, 则x到y之间的书与x相加一定都小于q,且都小于x+y,所以x+y-q是其中绝对值最小的,所以x到y之间的数与x的求和可以剪除。
5.若z = q,则返回z。
6.返回遍历过程中所标记的和。
代码:
#include #define N 1000 #define MAX 2147483647 int abs(int x) { return x < 0 ? -x : x; } void quicksort(int a[], int l, int u) { if(l >= u) return; int i, j, t; j = l; for(i = l; i < u; i++){ if(a[i] < a[u]){ t = a[i]; a[i] = a[j]; a[j] = t; j++; } } t = a[u]; a[u] = a[j]; a[j] = t; quicksort(a, l, j-1); quicksort(a, j+1, u); } int closest_num(int a[], int n, int q) { int i, j, t, sum, closest; closest = MAX; for(i = 0, j = n-1; i < j;){ t = a[i] + a[j] - q; if(abs(t) < closest){ closest = abs(t); sum = a[i] + a[j]; } if(t < 0) i++; else if(t > 0) j--; else break; } return sum; } int main() { int n, i, a[N], m, q, c; c = 1; while(scanf("%d", &n) != EOF && n != 0){ for(i = 0; i < n; i++) scanf("%d", a + i); quicksort(a, 0, n-1); scanf("%d", &m); printf("Case %d:\n", c); c++; while(m-- > 0){ scanf("%d", &q); printf("Closest sum to %d is %d.\n", q, closest_num(a, n, q)); } } return 0; }