UVa 10487 - Closest Sums

算是简单题,先算出来所有俩数的和存起来,在用二分查找找出最接近的值 ~

代码如下:

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;

int cmp(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}
int a[1000 + 2], b[25 + 2], s[1000000 + 10];
int main()
{
#ifdef test
    freopen("in.txt", "r", stdin);
#endif
    int  m, n, num = 0;
    while(cin >> m && m)
    {
        for(int i = 0; i < m; i++)
            cin >> a[i];
        qsort(a, m, sizeof(a[0]), cmp);
        cin >> n;
        for(int i = 0; i < n; i++)
            cin >> b[i];
        cout <<"Case "<<++num<<":"<<endl;
        int sum = -1;
        for(int i = 0; i < m; i++)
            for(int j = i + 1; j < m; j++)
                s[++sum] = a[i] + a[j];
        qsort(s, sum + 1, sizeof(s[0]), cmp);
        for(int i = 0; i < n; i++)
        {
            int max = sum + 1, min = 0, flag = 0;
            while(max > min)
            {
                int mid = (max + min) / 2;
                if(b[i] == s[mid])
                {
                    flag = 1;
                    break;
                }
                else if(b[i] > s[mid])
                    min = mid + 1;
                else
                    max = mid;
            }
            if(flag)
                cout<<"Closest sum to "<<b[i]<<" is "<<b[i]<<"."<<endl;
            else
            {
                int t = s[min];
                if(min + 1 <= sum)
                    t = abs(s[min + 1] - b[i]) > abs(s[max]- b[i]) ? s[max] : s[min + 1];
                if(min - 1 > -1)
                    t = abs(s[min - 1] - b[i]) > abs(t - b[i]) ? t : s[min - 1];
                cout<<"Closest sum to "<<b[i]<<" is "<<t<<"."<<endl;
            }
        }
    }
    return 0;
}

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