UVA - 10487 Closest Sums

题目大意:先给出 n 个数值, 再给出 m 个查找数值,要求每个查找数值从给出的 n 个数值中找到两个数,这两个数的和是所有任意两数的和中最接近查找数值的


解题思路:先给 n 个数值排序,然后二分查找

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

int main() {
	int n, m, cnt = 0, arr[1005];
	while (scanf("%d", &n), n) {
		printf("Case %d:\n", ++cnt);
		for (int i = 0; i < n; i++)
			scanf("%d", &arr[i]);
		sort(arr, arr + n);

		scanf("%d", &m);
		while (m--) {
			int query, left = 0, right = n - 1, min = 0x3f3f3f3f;
			scanf("%d", &query);
			while (left < right) {
				if (abs(min) > abs(arr[left] + arr[right] - query))
					min = arr[left] + arr[right] - query;
				arr[left] + arr[right] < query ? left++ : right--;
			}
			printf("Closest sum to %d is %d.\n", query, min + query);
		}
	}
	return 0;
}



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