uva 10487 - Closest Sums

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 (1Input 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


3
12
17
33
34
3
1
51
30
3
1
2
3
3
1
2
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.
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
int cmp(int a,int b)
{return a<b;}
int i,j,k,k1,k2,n,x,s,sum=0,a[1001],b[5005001];// a 1000, 1 999 ,wrong Y_Y re = =
int find(int l,int r)
{
 int m=(l+r)/2;
 if (b[m]==x) return m;
 if (l>r) return r;
 if (b[m]<x) find(m+1,r);
        else find(l,m-1);
}
int main()
{
 while (scanf("%d",&n),n)
 {
  s=0;
  for (i=1;i<=n;i++)
  scanf("%d",&a[i]);
  for (i=1;i<n;i++)
  for (j=i+1;j<=n;j++)
  b[s++]=a[i]+a[j];
  sort(b,b+s,cmp);
  printf("Case %d:
",++sum); scanf("%d",&n); while (n--) { scanf("%d",&x); if (x<=b[0]) k=0; else if (x>=b[s-1]) k=s-1; else { k=find(0,s-1); k1=k-1; k2=k+1; if (k1>=0 && abs(b[k1]-x)<abs(b[k]-x)) k=k1; if (k2<s && abs(b[k2]-x)<abs(b[k]-x)) k=k2; } printf("Closest sum to %d is %d.
",x,b[k]); } } return 0; }

좋은 웹페이지 즐겨찾기