Problem D
Closest Sums
Input: standard input
Output: standard output
Time Limit: 3 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 integer m giving the number of queries, 0 < m < 25. The next mlines 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.
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
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.
Piotr Rudnicki
题意:给出一个数组和一个数p,求数组中两个不同的数相加使得这两个数之和与这个数p最相近。
思路:先排序,在枚举一个数,之后二分查找第二个数,典型的二分,但是我用的是递归的二分查找。。
#include<iostream> #include<algorithm> using namespace std; int query[30]; int arry[1050]; const int maxint=0xfffffff; int minv,key1,key2,n,m,cnt,sum; bool cmp(int x,int y) { return x<y; } void dfs(int left,int right) { if(left>right) return; int r,t; int mid=(left+right)/2; if(mid!=cnt) { r=key2+arry[mid]-key1; t=key2+arry[mid]; if(r<0) r=r*-1; if(r<minv) minv=r,sum=t; } if(mid-1>=left) dfs(left,mid-1); if(mid+1<=right) dfs(mid+1,right); } int main() { int s=0; while(cin>>n&&n) { int i,j,k,r,t=0; for(i=0;i<n;i++) cin>>arry[i]; cin>>m; for(i=0;i<m;i++) cin>>query[i]; cout<<"Case "<<++s<<":"<<endl; sort(arry,arry+n,cmp); for(i=0;i<m;i++) { minv=maxint; key1=query[i]; for(j=0;j<n;j++) { cnt=j; key2=arry[j]; dfs(0,n-1); } cout<<"Closest sum to "<<key1<<" is "<<sum<<"."<<endl; } } return 0; }
[二分搜索]Closest Sums uva10487,布布扣,bubuko.com
原文:http://blog.csdn.net/zju_ziqin/article/details/20713899