[UVA10487]Closest Sums

Posted by John on 2016-01-19
Words 669 and Reading Time 3 Minutes
Viewed Times

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.

題意: 給你一些數字兩兩相加組成一個集合,再給你指定的數字,要你找出集合中離指定數字最接近的數。 想法:走訪所有元素相加做排序判斷即可。

第一次解這題的時候就直接暴力解了,後來用了Binary Search重寫了一次。

//使用Java的考生請注意,最外層的類別(class)需命名為 main 。 
//如果遇到超乎想像的狀況,請更改編譯器試看看!! 各編譯器特性不同!!
//預設測資、隨機測資、固定測資是用來幫助除錯用的。批改時,只看暗中測資是否通過!!
#‎include‬ <iostream>;
#include <cstdlib>;
using namespace std;
int all_ans[1000005] = {0};
int binary_search(int (&arr)[1000005] , int count , int find)
{
int upper = count - 1;
int lower = 0;
while(lower <= upper)
{
int mid = (upper + lower) / 2;
//printf("* %d %d\n",arr[mid],find);
if(find > arr[mid]) lower = mid + 1;
else if(find < arr[mid]) upper = mid - 1;
else return arr[mid];
}
//printf("->%d %d\n",lower,upper);
if(upper < 0) return arr[0];
else if(lower > count - 1) return arr[ count - 1];
else return abs(arr[lower]-find) > abs(arr[upper]-find) ? arr[upper] : arr[lower];
}
int main()
{
int n,m;
int num = 1;
int arr[1005] = {0};
while(scanf("%d",&amp;n) == 1 &amp;&amp; n)
{
printf("Case %d:\n",num++);
for(int i = 0 ; i < n ; ++i)
{
scanf("%d",&arr[i]);
}
int count = 0;
for(int i = 0 ; i < n ; ++i)
{
for(int j = i+1 ; j < n ; ++j)
{
all_ans[count++] = arr[i] + arr[j];
}
}
sort(all_ans+0,all_ans+count);
/*for(int i = 0 ; i < count ; ++i)
{
printf("%d ",all_ans[i]);
}
printf("\n");*/
scanf("%d",&m);
while(m--)
{
int query;
scanf("%d",&query);
printf("Closest sum to %d is %d.\n",query,binary_search(all_ans,count,query));
}
}
return 0;
}

>