uva10487/lower_bound使用

本文介绍了一种算法,用于从一组数中找到任意两数之和最接近给定目标值的组合。通过预处理所有可能的两数之和并进行排序,利用lower_bound查找最接近的目标值。

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

题目大意:
给出的数中,任意两个数相加,找出最接近query的数。

思路:
把任意两个数加起来之后,排序完之后,用lower_bound找到插入query的位置,然后找到它左右两边的与它最近的数。输出就可以了。

ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。

ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中第一个大于val的位置。

总结以下就是lower_bound返回第一个大于等于val的值的位置,upper_bound返回第一个大于val的值得位置,返回的是指针,所以要减去数组的头结点
代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
const int maxn = 1005;
int arr[maxn];
int b[maxn];
int sum[maxn*maxn];
int n, m;
int main() {
    int cas = 1;
    while(scanf("%d", &n)==1 && n) {

        int i, j;
        int h = 0;
        for(i=0; i<n; i++) {
            scanf("%d", &arr[i]);
            for(j=0; j<i; j++) {

                sum[h++] = arr[i]+arr[j];
            }

        }
        sort(sum, sum+h);

        scanf("%d", &m);

        for(i=0; i<m; i++) {        
            scanf("%d", &b[i]);
        }
        printf("Case %d:\n", cas++);
        for(i=0; i<m; i++) {
            printf("Closest sum to %d is ", b[i]);
            int pos = lower_bound(sum,sum+h,b[i])-sum;
            if(pos==0) {
                printf("%d.\n", sum[pos]);
                continue;
            }
            if(pos==h) {

                printf("%d.\n", sum[pos-1]);
                continue;
            }
            if(sum[pos]-b[i] < b[i]-sum[pos-1]) {

                printf("%d.\n",sum[pos]);
            }else  printf("%d.\n", sum[pos-1]);

        }

    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值