Sha 10487 closest sums

Source: Internet
Author: User

Uva_10487

Sort all sums after calculation, and then perform binary search.

# Include <stdio. h>
# Include < String . H>
# Include <stdlib. h>
Int CMP ( Const Void * _ P, Const Void * _ Q)
{
Int * P = ( Int *) _ P;
Int * Q = ( Int *) _ Q;
Return * P-* q;
}
Int A [ 1010 ], S [ 1000010 ];
Int Main ()
{
Int I, j, k, n, m, n, T, Min, mid, Max;
T = 0 ;
While ( 1 )
{
Scanf ( " % D " , & N );
If (N = 0 )
Break ;
N =0 ;
For (I = 0 ; I <n; I ++)
{
Scanf ( " % D " , & A [I]);
For (J = 0 ; J <I; j ++)
S [n ++] = A [I] + A [J];
}
Qsort (S, N, Sizeof (S [ 0 ]), CMP );
Printf ( " Case % d: \ n " , ++ T );
Scanf ( " % D " , & M );
For (I = 0 ; I <m; I ++)
{
Scanf ( " % D " , & K );
Min =0 ;
Max = N;
While ( 1 )
{
Mid = (min + max )/ 2 ;
If (S [Mid] = K)
Break ;
If (Min = mid)
Break ;
If (S [Mid]> K)
Max = mid;
Else
Min = mid;
}
Printf ( " Closest sum to % d is " , K );
If (Mid! = Min)
Printf ( " % D " , S [Mid]);
Else If (Max = N)
Printf (" % D " , S [Mid]);
Else
Printf ( " % D " , ABS (s [Min]-k) <ABS (s [Max]-k )? S [Min]: s [Max]);
Printf ( " . \ N " );
}
}
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.