/*
* UVA_11057.cpp
*
* Created on: 2013年11月4日
* Author: Administrator
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100010;
int leftt;
int rightt;
int a[maxn];
int n,m;
/**
* 在一组数据中找到这么两个数,使得他们的和等于指定数&&且这两个数之间的差值最小
*/
void search(int l,int r){
while(l < r){
if(a[l] + a[r] == m){
leftt = a[l];
rightt = a[r];
++l;
--r;
}else if(a[l] + a[r] < m){
++l;
}else if(a[l] + a[r] > m){
--r;
}
}
}
int main(){
while(scanf("%d",&n)!=EOF){
leftt = 0;//这里不要定义成left,否则可能会出现什么。。。ambiguous的错误(这是因为你在这里定义的变量与标准库或者是其他地方的变量冲突了...)
rightt = 0;
int i;
for(i = 0 ; i < n ; ++i){
scanf("%d",&a[i]);
}
sort(a,a+n);
scanf("%d",&m);
search(0,n-1);
printf("Peter should buy books whose prices are %d and %d.\n\n",leftt,rightt);
}
return 0;
}
(使用STL自带的排序功能进行排序7.3.12)UVA 11057 Exact Sum(在一组数据中找到这么两个数,使得他们的和等于指定数&&且这两个数之间的差值最小)
最新推荐文章于 2025-08-18 11:23:37 发布
本文提供了一种解决UVA_11057问题的有效算法实现,该问题要求从一组整数中找出两个数,使它们的和等于给定的目标值,并且这两个数之间的差值最小。通过先对输入进行排序,然后使用双指针技术来寻找符合条件的数对。

4万+

被折叠的 条评论
为什么被折叠?



