UVa 10487 Closest Sums

UVa 10487 Closest Sums
题目大意:给出n个数字,给出一个数字x,求出n个数字中哪两个数字的和与x最接近。
我的做法是这样的,把n个数字两两求和的结果存在数组里面,排序,去重(这一步无所谓)。每当给出一个x的时候,二分查找大于等于x的第一个数字,和小于x的最后一个数字。比较即可得出结果。
以下是我的代码:
#include < vector >
#include
< algorithm >
#include
< cstdio >
#include
< cstdlib >
using   namespace  std;

int  main()
{
    #ifndef ONLINE_JUDGE
    freopen(
" data.in " , " r " ,stdin);
    freopen(
" data.out " , " w " ,stdout);
    
#endif

    
int  case_num( 0 ),n;
    
while (scanf( " %d " , & n) == 1   &&  n)
    {
        vector
< int >  a,r;
        
for ( int  i = 0 ;i < n;i ++ )
        {
            
int  t;
            scanf(
" %d " , & t);
            a.push_back(t);
            
for ( int  j = 0 ;j < i;j ++ )
                r.push_back(a[j]
+ t);
        }

        sort(r.begin(),r.end());
        r.erase(unique(r.begin(),r.end()),r.end());

        
/*
        for(int i=0;i<r.size();i++)
        {
            if(i!=0)
                printf(" ");
            printf("%d",r[i]);
        }
        printf("\n");
        //
*/
        case_num
++ ;
        printf(
" Case %d:\n " ,case_num);

        
int  m;
        scanf(
" %d " , & m);
        
for ( int  i = 1 ;i <= m;i ++ )
        {
            
int  x;
            scanf(
" %d " , & x);

            
int  dist( 0x7f7f7f7f ),ans;
            vector
< int > ::iterator lpos(lower_bound(r.begin(),r.end(),x));
            
if (lpos != r.end())
            {
                
int  t =* lpos;
                
if (dist > abs(t - x))
                {
                    dist
= abs(t - x);
                    ans
= t;
                }
            }
            
if (lpos != r.begin())
            {
                
int  t =* (lpos - 1 );
                
if (dist > abs(t - x))
                {
                    dist
= abs(t - x);
                    ans
= t;
                }
            }

            printf(
" Closest sum to %d is %d.\n " ,x,ans);
        }
    }
}

你可能感兴趣的:(UVa 10487 Closest Sums)