forked from ajahuang/UVa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUVa 10487 - Closest Sums.cpp
63 lines (57 loc) · 1.58 KB
/
UVa 10487 - Closest Sums.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int dist(int n1, int n2)
{
return n1 >= n2? n1 - n2 : n2 - n1;
}
int main()
{
size_t Case = 1, n;
while (cin >> n, n > 0)
{
cout << "Case " << Case++ << ":" << endl;
vector<int> numbers(n);
for (size_t i = 0; i < n; ++i)
cin >> numbers[i];
sort(numbers.begin(), numbers.end());
size_t m;
cin >> m;
while ( m-- )
{
int query;
cin >> query;
size_t L = 0, U = numbers.size() - 1;
int sum = 0;
if (numbers[0] != numbers.back())
{
sum = numbers[0] + numbers.back();
// Find a sum as close to query as possible.
while (L < U)
{
// "a sum of two distinct numbers"
if (numbers[L] != numbers[U]
&& dist(query, numbers[L] + numbers[U])
< dist(query, sum))
{
sum = numbers[L] + numbers[U];
}
if (numbers[L] + numbers[U] == query)
break;
else if (numbers[L] + numbers[U] < query)
++L;
else
--U;
}
}
cout << "Closest sum to "
<< query
<< " is "
<< sum
<< "."
<< endl;
}
}
return 0;
}