PKU Acm2785--4 Values whose Sum is 0~~ bidirectional search

Source: Internet
Author: User

The meaning of the topic is very clear, ABCD four sets, extracting a number from each set, and adding four numbers equals 0 of the combined number.

Because n maximum reaches 4000, so, the method of violence can not live, is the time limit is 15000MS also not.

But we can search two-way, that is binary search.

First find the CD of the two sets of 22 pairs of new collection CD, and then in the collection from the CD to look for AB set 22 paired and K negative number of how many. The Upper_bound and Lower_bound functions can be solved quickly.

To put it simply, a+b+c+d=0, calculate the C + d,a + b =-(c + D) and look it up in the collection CD.

The following is the code for the AC:

#include <iostream> #include <algorithm> #include <cstdio>using namespace Std;int n;int a[4005], b[ 4005], c[4005], d[4005];int cd[4005 * 4005];void solve () {int I, J, k;for (i = 0; i < n; i++) for (j = 0; J < N; j + +) cd[ I * n + j] = C[i] + d[j];        For collection Cdsort (CD, CD + n * n);//Sort __int64 ans = 0;for (i = 0; i < n; i++) {for (j = 0; J < N; j + +) {k = A[i] + B[j];ans + = Upper_bound (CD, CD + N * N,-K)-Lower_bound (CD, CD + N * N,-K);   Find out how many elements are equal to-K}}printf ("%i64d\n", ans);} int main () {int i;scanf ("%d", &n), for (i = 0; i < n; i++) {scanf ("%d", &a[i]), scanf ("%d", &b[i]), scanf ("%d", and Amp C[i]); scanf ("%d", &d[i]);} Solve (); return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

PKU Acm2785--4 Values whose Sum is 0~~ 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.