4 Values whose Sum is 0
程序员文章站
2022-06-17 19:48:34
...
题解:
1.计算出A,B中所有元素两两的和,放到s1里。
2.计算C,D中所有元素两两的和,放到s2里。
3.对s1进行排序。
4.遍历s2的每一个元素,用二分法的方式在s1里找出和它相加为0的值
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#define LL long long
using namespace std ;
LL a[4001],b[4001],c[4001],d[4001],s1[16100000],s2[16100000],ans = 0;
int main()
{
int n;
scanf("%d",&n);
for(int i = 0 ; i< n ; i++)
scanf("%lld%lld%lld%lld",&a[i],&b[i],&c[i],&d[i]);
int len = 0;
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < n ; j++)
{
s1[len] = a[i]+b[j];
s2[len++] = c[i]+d[j];
}
sort(s1,s1+len);
for(int i = 0 ; i < len ; i++)
{
int l = 0 ,r = len-1,mid;
while(l<r)//不能加等号,万一l == r,但是s1[mid]>=-s2[i],就一直重复r = mid,无限循环
{
mid = (l+r)/2;
if(s1[mid]<-s2[i])
l = mid+1;
else
r = mid;
}
while(s1[l] == -s2[i]&&l<len)//等于-s2[i]的值可能不止一组,但是l代表的是最小的。
{
l++;
ans++;
}
}
cout<<ans<<endl;
return 0;
}
推荐阅读
-
4 Values whose Sum is 0 POJ - 2785
-
4 Values whose Sum is 0
-
POJ 2785 4 Values whose Sum is 0
-
POJ 2785 4 Values whose Sum is 0(hash)
-
第四十二题 UVA1152 和为0的4个值 4 Values whose Sum is 0
-
POJ-2785 4 Values whose Sum is 0(二分+双指针)
-
POJ2785 4 Values whose Sum is 0
-
4 Values whose Sum is 0 POJ - 2785
-
4 Values whose Sum is 0 (折半枚举)
-
POJ-3441:4 Values whose Sum is 0--多元素之和判定