10487-closest sums
Time limit:3.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_ problem&problem=1428
Given is a set of integers and then a sequence of queries. A query gives you with a number and asks to find a sum of two distinct numbers from the set, which are closest to the query numb Er.
Input
Input contains multiple cases.
Each case is starts with a integer n (1<n<=1000), which indicates, how many numbers the set of integer. Next n lines contain n numbers. The course there is only one, single. The next line contains a positive integerm giving the number of queries, 0 < M < 25. The next m lines contain an integer of the query, one on line.
The Input is terminated by a case whose n=0. Surely, this case needs no processing.
Output
Output should is 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 would be such that no ties would 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.
Closest sum to 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.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Train of thought: Can direct O (n^2) Enumerate the closest number, but may wish to sort after each number a[i], in a[i+1]~a[n-1] between the two find and A[i] and closest to the number of query, Complexity O (nlog N)
Complete code:
/*0.012s*/#include <cstdio> #include <cstdlib> #include <algorithm> using namespace std;
#define SF scanf #define PF printf const int inf=0x3f3f3f3f;
int a[1005];
int cas = 0, n, m, query, closest, diff, I, J; inline void Find () {if (j = = n | | J!= i + 1 && diff-a[j-1] < a[j]-diff) {if (d)
IFF-A[J-1] < ABS (closest-query)) closest = A[i] + a[j-1];
else {if (A[j]-diff < Abs (closest-query)) closest = A[i] + a[j]; int main () {while (SF ("%d", &n), N) {for (i = 0; i < n; ++i) s
F ("%d", &a[i]);
Sort (A, a + N);
SF ("%d", &m);
PF ("Case%d:\n", ++cas);
while (m--) {SF ("%d", &query);
closest = INF; for (i = 0; i < n-1 ++i) {diff= Query-a[i];
j = Lower_bound (A + i + 1, a + N, diff)-A;
Find ();
PF ("Closest sum to%d are%d.\n", query, closest);
} return 0; }