Semi-enumeration (bidirectional search)

Source: Internet
Author: User

There are four Series A, B, C, and D with N integers. Take a number from each sequence so that the sum of the four numbers is 0. Find the number of such combinations.

Input

N = 6

A = {-45,-41,-36,-36, 26,-32}

B = {22,-27, 53, 30,-38,-54}

C = {42, 56,-37,-75,-10,-6}

D = {-16, 30, 77,-46, 62, 45}

Select a total of N4 cases from the four columns, and all cases are judged as unfeasible. However, if we divide them into AB and CD, we can solve the problem quickly. If you select only N2 combinations from two columns, You can enumerate them. After extracting a and B From A and B, C + D =-(A + B) needs to be extracted from C and D to make the sum 0 ). Therefore, the N2 methods that retrieve numbers from C and D are enumerated and sorted to perform binary search. The complexity of this algorithm is O (n2logn ).

1 # include <iostream> 2 # include <algorithm> 3 # include <cstdio> 4 using namespace STD; 5 6 # define max_n 1000 7 8 int N; 9 int A [max_n], B [max_n], C [max_n], d [max_n]; 10 int CD [max_n * max_n]; // combination of numbers in C and D 11 12 Void solve () 13 {14 // enumeration all methods for extracting numbers from C and D 15 for (INT I = 0; I <n; I ++) 16 {17 for (Int J = 0; j <n; j ++) 18 {19 CD [I * n + J] = C [I] + d [J]; 20} 21} 22 sort (Cd, CD + N * n ); 23 long res = 0; 24 for (INT I = 0; I <n; I ++) 25 {26 for (Int J = 0; j <N; j ++) 27 {28 int Cd =-(A [I] + B [J]); 29 // take out part 30 res + = upper_bound (Cd, CD + N * n, Cd)-lower_bound (Cd, CD + N * n, CD); 31} 32} 33 printf ("% LLD \ n", Res); 34} 35 36 37 int main () 38 {39 CIN> N; 40 for (INT I = 0; I <n * 4; I ++) 41 {42 switch (I/6) 43 {44 case 0: 45 CIN> A [I % 6]; 46 break; 47 Case 1: 48 CIN> B [I % 6]; 49 break; 50 Case 2: 51 CIN> C [I % 6]; 52 break; 53 Case 3: 54 CIN> d [I % 6]; 55 break; 56 default: 57 break; 58} 59} 60 solve (); 61 Return 0; 62}

 

Semi-enumeration (bidirectional search)

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.