二分贪心04

来源:互联网 发布:斐波那契数列java递归 编辑:程序博客网 时间:2024/06/06 15:42

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 2 28 ) 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).

题目大意:给你一些数,每行4个,从每列里选一个数,让这四个数的和为0,问有多少种取法


设四个数组,让前两个和后两个分别相加,然后排序,前后迂回,一个从前往后,另一个从后往前,high<0结束

#include<iostream>#include<algorithm>#include<stdio.h>using namespace std;int ab[4000*4000];int cd[4000*4000];int a[4001],b[4001],c[4001],d[4001];int main(){      int n,i,j,k,sum,p;      scanf("%d",&n);      for(i=0;i<n;i++)      {          scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);      }        int t=0;      for(i=0;i<n;i++)        for(j=0;j<n;j++)       {             ab[t]=a[i]+b[j];            t++;        }        int q=0;      for(i=0;i<n;i++)        for(j=0;j<n;j++)      {            cd[q]=c[i]+d[j];            q++;        }      sort(ab,ab+t);//这个地方要注意,写的时候sort(ab,ab+t+1),一直出错,      sort(cd,cd+q);      int ans=0;      int low=0,high=n*n-1,mid;      for(i=0;i<t;i++)      {            while(high>=0&&ab[i]+cd[high]>0) high--;//在另一个数组中找数,因为已经排序过,所以>0说明cd【】数组里的数大,直接下一个        if(high<0) break;        int low=high;        while(low>=0&&ab[i]+cd[low]==0)        {            ans++;            low--;//找到一个之后,因为cd中有可能出现相同的数,所以继续往下找         }       }      cout<<ans<<endl;       return 0;}

0 0
原创粉丝点击