VJ链接
题意
给出n行,每行都是4个数据。每行可以任意选出来一个数据,求选出来的四个数相加结果为0的情况共有多少种。
思路
可以先将两组数据合并成一组数据,然后通过二分函数找出与合并的来的数的相反数在另外两组数据中共有多少个,进行累加就可以得到结果。
两个二分函数
upper_bound:返回第一个大于的元素下标
lower_bound:返回第一大于等于的元素下标
所以,upper_bound-lower_bound代表有多少于恰好相同的元素
代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[4001],b[4001],c[4001],d[4001];
int sum[4001*4001];
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
int l=0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
sum[l++]=a[i]+b[j];//合并前两项的数据
int ans=0;
sort(sum,sum+l);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)//依次用sum中的数据进行比较,把能与-sum相同的情况数目记下来
ans+=upper_bound(sum,sum+l,-c[i]-d[j])-lower_bound(sum,sum+l,-c[i]-d[j]);
printf("%d\n",ans);
return 0;
}