传送:UVA - 10487
10487 Closest Sums
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.
思路:首先先输入一堆数,然后排个序,再算出所有的不同的两个数的和,存入另一个数组(用set判重),对该数组排序,然后二分查找结果,注意这里数组要开大点,因为最大1000 *(1000 + 1)/ 2有500500,这里RE了一次
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <set> #define LL long long #define INF 0x3fffffff using namespace std; int n, m; int a[501000]; int sum; int main() { int cas = 1; while(scanf("%d", &n), n) { int tmp[1005]; for(int i = 0; i < n; i++) { scanf("%d", &tmp[i]); } sort(tmp, tmp + n); sum = 0; set<int> se; for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { int t = tmp[i] + tmp[j]; if(!se.count(t)) { se.insert(t); a[sum++] = t; } } } sort(a, a + sum); //for(int i = 0; i < sum; i++) printf("%d\n", a[i]); printf("Case %d:\n", cas ++); scanf("%d", &m); while(m--) { int tt; scanf("%d", &tt); if(tt >= a[sum - 1]) { printf("Closest sum to %d is %d.\n", tt, a[sum - 1]); } else if(tt <= a[0]) { printf("Closest sum to %d is %d.\n", tt, a[0]); } else { int fir = 0, fin = sum - 1; while(fir < fin) { int m = fir + (fin - fir) / 2; if(a[m] < tt) fir = m + 1; else fin = m; } int ans; if(abs(a[fin] - tt) > abs(a[fin - 1] - tt)) ans = a[fin - 1]; else ans = a[fin]; printf("Closest sum to %d is %d.\n", tt, ans); } } } return 0; }