当前位置:编程学习 > C/C++ >>

UVa 10487 - Closest Sums

原题:
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.

题目大意:
给出由一些数字组成的集合,然后再输入一个字, 找出集合中不同的两个数的和最接近输入这个数的值。


分析与总结:
先求出这个集合中所有两个数和的情况,然后进行排序和去重,再对输入的数字进行二分查找即可。


代码:
[cpp] 
/*
 * 10487 - Closest Sums
 * Time:  0.152s
 * Author: D_Double
 */ 
#include<iostream> 
#include<cstdio> 
#include<vector> 
#include<cmath> 
#include<algorithm> 
using namespace std; 
int arr[1005]; 
vector<int>vt; 
vector<int>vt2; 
 
int main(){ 
#ifndef ONLINE_JUDGE 
    freopen("input.txt","r",stdin); 
    freopen("output.txt","w",stdout); 
#endif 
    int n,m,cas=1,q; 
    while(scanf("%d",&n), n){ 
        vt.clear(); 
 
        for(int i=0; i<n; ++i)  
            scanf("%d",&arr[i]); 
         
        for(int i=0; i<n; ++i){ 
            for(int j=i+1; j<n; ++j){ 
                vt.push_back( arr[i]+arr[j] );  
            } 
        } 
        sort(vt.begin(), vt.end()); 
        vt2.clear(); 
        vt2.push_back(vt[0]); 
         
        for(int i=1; i<vt.size(); ++i) 
            if(vt[i]!=vt[i-1]) vt2.push_back(vt[i]); 
         
        printf("Case %d:\n", cas++); 
        scanf("%d",&m); 
         
        for(int i=0; i<m; ++i){ 
            scanf("%d", &q);   
            vector<int>::iterator it; 
            it = lower_bound(vt2.begin(), vt2.end(), q); 
            if(*it==q) printf("Closest sum to %d is %d.\n", q, q); 
            else { 
                int min = *it; www.zzzyk.com
                if(it!=vt2.begin() && abs(*(it-1)-q) < abs(min-q)) min = *(it-1); 
                printf("Closest sum to %d is %d.\n", q, min); 
            }  
        } 
    } 
    return 0; 

 


作者:shuangde800
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,