Link:
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_ problem&problem=1428
Original title:
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 integer m 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.
The main effect of the topic:
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Give a set of numbers, and then enter a word to find the number of different two in the collection and the nearest value to enter.
Analysis and Summary:
First find out all the two numbers in this set and the situation, and then sort and go to the weight, and then the input of the number of binary lookup can be.
Code:
* * * 10487-closest sums * time:0.152s * author:d_double/#include <iostream> #include <cstdio>
#include <vector> #include <cmath> #include <algorithm> using namespace std;
int arr[1005];
vector<int>vt;
vector<int>vt2;
int main () {#ifndef Online_judge freopen ("Input.txt", "R", stdin);
Freopen ("Output.txt", "w", stdout);
#endif int n,m,cas=1,q;
while (scanf ("%d", &n), N) {vt.clear ();
for (int i=0; i<n; ++i) scanf ("%d", &arr[i]);
for (int i=0; i<n; ++i) {for (int j=i+1; j<n; ++j) {vt.push_back (arr[i]+arr[j));
} sort (Vt.begin (), Vt.end ());
Vt2.clear ();
Vt2.push_back (Vt[0]);
for (int i=1; i<vt.size (); ++i) if (vt[i]!=vt[i-1) Vt2.push_back (vt[i)); printf ("Case%d:\n ", cas++);
scanf ("%d", &m);
for (int i=0; i<m; ++i) {scanf ("%d", &q);
Vector<int>::iterator it;
it = Lower_bound (Vt2.begin (), Vt2.end (), q);
if (*it==q) printf ("Closest sum to%d is%d.\n", Q, Q);
else {int min = *it;
if (It!=vt2.begin () && ABS (* (IT-1)-Q) < ABS (min-q)) min = * (it-1);
printf ("Closest sum to%d are%d.\n", Q, Min);
}} return 0; }
Author: csdn Blog shuangde800