Solution of 10487 - Closest Sums

Problem Description
source:https://uva.onlinejudge.org/external/104/10487.html

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 42 46 49 5 3 12 17 33 34 3 42 46 47

Sample Output

Case 1: Closest sum to 42 is 45. Closest sum to 46 is 46. Closest sum to 49 is 50. Case 2: Closest sum to 42 is 45. Closest sum to 46 is 46. Closest sum to 47 is 46.

Solution:
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include<stdio.h>
#include<stdlib.h>

using namespace std;
long int sum[1000010];
int main()
{
    long int n,m,i,j,k,range,number[1050],query,min,dist,t=0,close;
    //freopen("input.txt","r",stdin);
    while(scanf("%ld",&n)==1)
    {
        if(n==0)
            break;
        t+=1;
        for(i=0;i<n;i++)
            scanf("%ld",&number[i]);
        k=0;
        for(i=0;i<n-1;i++)
            for(j=i+1;j<n;j++)
                sum[k++]=number[i]+number[j];

        scanf("%ld",&m);
        printf("Case %ld:\n",t);
        for(i=1;i<=m;i++)
        {
            scanf("%ld",&query);
            min=2147483647;
            for(j=0;j<k;j++)
            {
                dist=abs(query-sum[j]);
                if(min>dist)
                {
                    min=dist;
                    close=sum[j];
                }
            }
            printf("Closest sum to %ld is %ld.\n",query,close);
        }

    }
    return 0;
}
image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience