UVa 10487 - Closest Sums

本文介绍了一个算法问题——给定一组整数和一系列查询,对于每个查询找到集合中两个不同数字之和,该和最接近查询数。通过先计算所有可能的两两组合的和,并将这些和排序,然后遍历排序后的数组来找出最接近查询数的和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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.

Piotr Rudnicki

相加+排序

#include <stdio.h>
#include <string.h>
#include <math.h>
int a[1000];
int sum[1000000];
int top;
int cmp(const void *e,const void *f)
{
    return *(int *)e-*(int *)f;
}
int main()
{
    int i,j,n,m,s,t,k,min;
    int tem=1;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0)
        {
            break;
        }
        for(i=0;i<=n-1;i++)
        {
            scanf("%d",&a[i]);
        }
        for(i=0,top=0;i<=n-1;i++)
        {
            for(j=i+1;j<=n-1;j++)
            {
                sum[top]=a[i]+a[j];
                top++;
            }
        }
        qsort(sum,top,sizeof(sum[0]),cmp);
        scanf("%d",&m);
        printf("Case %d:\n",tem);tem++;
        for(i=0;i<=m-1;i++)
        {
            scanf("%d",&k);
            min=sum[0];
            for(j=1;j<=top-1;j++)
            {
                if(abs(sum[j]-k)<=abs(min-k))
                {
                    min=sum[j];
                }else
                {
                    break;
                }
            }
            printf("Closest sum to %d is %d.\n",k,min);
        }
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值