Two numbers for S

Source: Internet
Author: User

Enter an incremental sorting array and a number S, and search for two numbers in the array. Yes, their sum is exactly S. If there are multiple pairs of numbers and the sum is equal to S, the product of the two numbers is the smallest. Input: each test case contains two rows: the first row contains an integer n and k, and n represents the number of elements in the array, and k represents the sum of the two. Where 1 <= n <= 10 ^ 6, k is the second line of int contains n integers, each array is of the int type. Output: two numbers are output for each test case. A small number is output first. If not, output the "-1-1" sample input: 6 151 2 4 7 11 15 sample output: 4 11 idea: because the order has been sorted, if there are two numbers, it may be a relatively large number, a relatively small number, or a relatively equal number! So let's set a n1 = min (that is, a [0]), n2 = max (that is, a [n-1]), which is actually n1 = a [low], low = 0 start, n2 = a [high], high = n-1 start, then n1 + n2 compare with S (We Need To sum), if>, n2 = a [-- high]; If <, n1 = a [++ low], and if =, use mul to save the product, and save two numbers, because there may be more than one pair of numbers, as long as the product is small! Scan until low> = high ends! Code AC: [cpp] # include <stdio. h> # include <stdlib. h> int main () {long int n, I, low, high; long int mul; long int s, * data, m1, m2, flag; while (scanf ("% ld", & n, & s )! = EOF) {data = (long int *) malloc (sizeof (long int) * n); for (I = 0; I <n; I ++) // {scanf ("% ld", & data [I]);} m1 =-1; m2 =-1; low = 0; high = n-1; mul =-1; flag = 1; while (low

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.