您的位置:首页 > 其它

uva 10487 - Closest Sums

2012-09-06 19:31 423 查看
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
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.

#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:\n",++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.\n",x,b[k]);
}
}
return 0;
}

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: