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.
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
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.
题目:给你n个数字set[1~n],以及m个数字query[1-m],对于每个query[i]找到对应的两个set[j],set[k]使得他们的和最接近query[i]。
解析:用二分求解,比较简单。详见代码。
#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; }