10487 - Closest Sums
Time limit: 3.000 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 integerm 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.
思路:可以直接O(N^2)枚举最接近的数,但是不妨排序后,对每个数a[i],在a[i+1]~a[n-1]之间二分查找与a[i]之和最接近query的数,复杂度O(Nlog N)
完整代码:
/*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 (diff - 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)
sf("%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 is %d.\n", query, closest);
}
}
return 0;
}