二分贪心d

来源:互联网 发布:关键词分分析软件 编辑:程序博客网 时间:2024/05/20 05:08

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




这个题需要用二分,如果不用二分的话会超时,先求出所有a+b的值,然后用每个c+d的值二分查找a+b的值。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int x,l,r,m,k;
int main()
{
    vector<int>f;
int e;
cin>>e;
int a[4005],b[4005],c[4005],d[4005],x1=0,i,j,y=0;
for(i=0;i<e;i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
for(i=0;i<e;i++)
{
for(j=0;j<e;j++)
{
f.push_back(a[i]+b[j]);
x1++;
    }
}
sort(f.begin(),f.end());
for(i=0;i<e;i++)
{
for(j=0;j<e;j++)
{
    //cout<<y<<endl;
x=-c[i]-d[j];
l=0;
r=x1-1;
while(l<=r)
{
    //cout<<y<<endl;
m=(l+r)/2;
if(f[m]>x)
r=m-1;
else
if(f[m]<x)
l=m+1;
else
{
for(k=m;k>=0;k--)
{
if(f[k]==x)
y++;
else
break;
}
for(k=m+1;k<x1;k++)
{
if(f[k]==x)
y++;
else
break;
}
break;
}
}

}
}
cout<<y;
}

0 0
原创粉丝点击