题目:

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 -46
26 -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).
 
 
题意:
给一个n*4的矩阵,输入n*4个数,在每一列找一个数,使得四个数的和为0;
 
分析:
先分别求出a和b,c和d两列任意两个数的和存放到相应的数组,将cd的和进行排序后,再用二分法进行查找;二分查找的时候注意,倘若中间的数据符合条件的话要再往两边进行查找,因为不能排除有多个数字相等的情况
 
注意:
求第二组数据的时候,根据提交的结果是不需要初始化total的;
 
 
AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=;
int a[N],b[N],c[N],d[N];
int ab[N*N],cd[N*N];
int main()
{
int n,total=,i,j;
while (cin>>n)
{
for (i=;i<n;i++)
cin>>a[i]>>b[i]>>c[i]>>d[i];
int num1=,num2=;
for (i=;i<n;i++)
for (j=;j<n;j++)
{
ab[num1++]=a[i]+b[j];
cd[num2++]=-(c[i]+d[j]);
}
sort (cd,cd+num2);
for (i=;i<num1;i++)
{
int mid,up=num2-,low=;
while (low<=up)
{
mid=low+(up-low)/;
if (ab[i]==cd[mid])
{
total++;
for (j=mid+;j<=up;j++)
{ if (ab[i]==cd[j])
total++;
else
break;
}
for (j=mid-;j>=low;j--)
{
if (ab[i]==cd[j])
total++;
else
break;
} break;
}
else
{
if (ab[i]>cd[mid])
low=mid+;
else
up=mid-;
}
}
}
cout << total << endl;
} return ;
}

最新文章

  1. WebApi Post 后台无法获取参数的解决方案
  2. 由一个异常开始思考springmvc参数解析
  3. 倍增法-lca codevs 1036 商务旅行
  4. 使用仓库管理器——Sonatype Nexus的九大理由
  5. CSDN&mdash;&mdash;【低调的草原狼】&mdash;&mdash;Ext4.2学习目录整理
  6. hadoop_集群安装_1
  7. android AudioRecorder简单心得
  8. Git远程仓库的使用(三)
  9. 高可用开源方案 Keepalived VS Heartbeat对比
  10. Java动态数组
  11. 基于Vue.js的大型报告页项目实现过程及问题总结(一)
  12. opencv基本图像操作
  13. HJ212 CRC 16 (C#)
  14. python自动化开发-[第一天]-练习题
  15. [20170625]12c Extended statistics.txt
  16. scala 爬虫 去除不能存储的特殊字符
  17. 10-04 Java 权限修饰符,类及其组成常见的修饰符
  18. 关于sdl_ttf使用字体库加载失败的问题
  19. Linux基础-网络配置
  20. 【Android】21.2 2D图形图像处理(Canvas和Paint)

热门文章

  1. 第二季第十天 es6新特性新特性
  2. Maven--优化依赖
  3. BBS数据库设计
  4. 刷题41. First Missing Positive
  5. 【iOS学习笔记】UITextField中的输入检测——限制只能输入数字和小数点
  6. 【转】Fst指数
  7. java threadlocal 背景 本质
  8. 函数动态传参,命名空间,gloabal,nonlocal关键字
  9. 图像的手绘效果(Python)
  10. python-django电商项目-需求分析架构设计数据库设计_20191115