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.
题意:给你n个数,求出两两之和,然后m次询问,找与当前询问的数相等的数并输出,如果没有相等的就输出最相近的数。
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <algorithm> #include <set> #include <map> #include <queue> using namespace std; const int inf=0x3f3f3f3f; int a[1010],q[30]; int sum[1000010]; int main() { int n,m,i,j; int cnt=0; int cas=1; int res; while(~scanf("%d",&n)) { if(n==0) break; cnt=0; for(i=0; i<n; i++) scanf("%d",&a[i]); for(i=0; i<n-1; i++) for(j=i+1; j<n; j++) { sum[cnt]=a[i]+a[j]; cnt++; } sort(sum,sum+cnt); scanf("%d",&m); for(i=0; i<m; i++) scanf("%d",&q[i]); printf("Case %d:\n",cas++); for(i=0; i<m; i++) { if(q[i]<=sum[0]) res=sum[0]; else if(q[i]>=sum[cnt-1]) res=sum[cnt-1]; else { for(j=0; j<cnt; j++) { if(sum[j]<q[i]) continue; else { if(abs(sum[j]-q[i])<abs(sum[j-1]-q[i])) res=sum[j]; else res=sum[j-1]; break; } } } printf("Closest sum to %d is %d.\n",q[i],res); } } return 0; }