POJ 2785 4 Values whose Sum is 0 (bidirectional search + two points)

Source: Internet
Author: User

Test instructions: Give 4 arrays, choose a number from each array, and find out the number of 4 and 0 schemes.

Analysis: Violence time complexity is n^3, certainly not. So consider first the AB, the CD, and the separate to find out. -(A+B) =c+d that satisfies the condition, the summation complexity is n*n. The AB array is-(A+B), the CD array is (C+D).

From the CD array, find the equivalent of the AB array. You can sort the array first, and then use the binary search to find it. The complexity is O (N*N*LOGN).

#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include < algorithm> #include <queue> #include <set> #include <map> #include <vector> #include < Cmath> #define LL __int64#define INF 0x3fffffff#define M 4005using namespace Std;int n;int a[m],b[m],c[m],d[m];int Ab[M    *m],cd[m*m];int Main () {//freopen ("D:\\test.txt", "R", stdin);         while (Cin>>n) {for (int i=0;i<n;i++) {scanf ("%d%d%d%d", &a[i],&b[i],&c[i],&d[i]);        } int k1=0;            for (int. i=0;i<n;i++) {for (int j=0;j<n;j++) {ab[k1++]=-a[i]-b[j];        }} int k2=0;            for (int. i=0;i<n;i++) {for (int j=0;j<n;j++) {cd[k2++]=c[i]+d[j];        }} sort (AB,AB+K1);        Sort (CD,CD+K2);        ll Ans=0;        for (int i=0;i<k1;i++) {ans+=upper_bound (Cd,cd+k2,ab[i])-lower_bound (Cd,cd+k2,ab[i]);        }cout<<ans<<endl; } return 0;}


POJ 2785 4 Values whose Sum is 0 (bidirectional search + two points)

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.