POJ2785_Values whose Sum is 0_二分

来源:互联网 发布:文化部网络动漫黑名单 编辑:程序博客网 时间:2024/05/16 07:11

题目描述

4 Values whose Sum is 0
Time Limit: 15000MS Memory Limit: 228000KTotal Submissions: 14563 Accepted: 4163Case Time Limit: 5000MS

Description

The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .

Input

The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 228 ) that belong respectively to A, B, C and D .

Output

For each input file, your program has to write the number quadruplets whose sum is zero.

Sample Input

6-45 22 42 -16-41 -27 56 30-36 53 -37 77-36 30 -75 -4626 -38 -10 62-32 -54 -6 45

Sample Output

5

Hint

Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).

解题报告

四个数组,枚举复杂度必然O(N^4)。

咱们只得想尽一切办法降低复杂度。不如将其两两数组合为一组,遍历A组,二分查找B组。

这样时间复杂度降低到了O(2*N^2+N^2*logN)=O(N^2logN);

对于数据范围4000以内的数据,可以接受。

需要注意的是,A中某元素在B组查找时,相等的元素也需计算。我的代码是找到B中和为零的元素后再向前后统计相等的个数,这样的效率太低。。。。

理应用upperbound与lowerbound会快很多。

2069840BillywongAAccepted49716 KB4797 msG++1760 B2014-03-21 20:20:29

代码

#include <iostream>#include <stdio.h>#include <algorithm>using namespace std;int cube[4][5000];int doub[2][5000*5000];int n;int bs(int x){    int low=0,high=n*n-1,mid,res = -1,num;        while(low<=high)    {        mid=(low+high)>>1;                     if(doub[1][mid]+doub[0][x]==0)                     {           res = mid;       break;        }        else if(doub[1][mid]+doub[0][x]<0)                      low=mid+1;        else                        high=mid-1;}num=0;for(int i=mid;i>=0;i--)            if(doub[1][i]+doub[0][x]==0)                    num++;            else                break;    for(int i=mid+1;i<n*n;i++)            if(doub[1][i]+doub[0][x]==0)                num++;            else                break;    return num;}int main(){    while(scanf("%d",&n)!=EOF)    {    for(int i = 1; i <= n;i ++)        scanf("%d%d%d%d",&cube[0][i],&cube[1][i],              &cube[2][i],&cube[3][i]);    int num=-1;    for(int i = 1;i <= n;i ++)    for(int o = 1;o <= n;o ++){        doub[0][++num] = cube[0][i]+cube[1][o];        doub[1][num] = cube[2][i]+cube[3][o];    }    sort(doub [0],doub [0]+ n*n);    sort(doub [1],doub [1] + n*n);    num=0;    for(int i=0;i<n*n;i++)            num+=bs(i);        //num+=(upper_bound(doub[1],doub[1]+n*n-1,doub[0][i])-lower_bound(doub[1],doub[1]+n*n-1,doub[0][i])) + 1;        //printf("upper=%d   lower=%d    num=%d\n   ",upper_bound(doub[1],doub[1]+n*n,doub[0][i]),lower_bound(doub[1],doub[1]+n*n,doub[0][i]),num);    printf("%d\n",num);    }    return 0;}


0 0
原创粉丝点击