Uvs: 10487

Source: Internet
Author: User

Question: 10487-Closest Sums


Give a group of data, and then give m query numbers. It is required to find the sum of the two data in this group and the data closest to this query, and output the sum of the two data.

Solution: Perform binary search. If this is found, the query value is output, but note that the query cannot be found: the closest value here is not necessarily the previous data at the time when it cannot be found, so maintain the value of the nearest number to be queried.


Code:

#include <stdio.h>#include <algorithm>#include <stdlib.h>using namespace std;const int N = 1005;int s[N];int n, q;int min (const int a, const int b) {if (a == 0)return b;return abs(a - q) < abs (b - q)? a: b;}int search () {int l = 0;int r = n - 1;int sum = 0;while (l <= n - 1 && r >= 0 && l < r) {if (s[l] + s[r] < q) {sum = min (sum, s[l] + s[r]);l++;}else if (s[l] + s[r] > q) {sum = min (sum , s[l] + s[r]);r--;}elsereturn s[l] + s[r]; }return sum;}int main () {int m;int t = 0;while (scanf ("%d", &n), n) {for (int i = 0; i < n; i++)scanf ("%d", &s[i]);sort (s, s + n);scanf ("%d", &m);printf ("Case %d:\n", ++t);for (int i = 0; i < m; i++) {scanf ("%d", &q);printf ("Closest sum to %d is %d.\n", q, search ());}}return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.