博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
4 Values whose Sum is 0 (二分+排序)
阅读量:6876 次
发布时间:2019-06-26

本文共 1684 字,大约阅读时间需要 5 分钟。

题目:

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

 

转载于:https://www.cnblogs.com/lisijie/p/7289457.html

你可能感兴趣的文章
Flutter Web - 目标全平台开发的Flutter再下一城!
查看>>
RAID-10 阵列的创建(软)
查看>>
小菜鸡进阶之路-First week
查看>>
【原创翻译】布尔值(boolean)
查看>>
关于scrapy的piplines
查看>>
Windows Server 2008 FTP用户目录隔离模式
查看>>
python实现linux下指定目录下文件中的单词个数统计
查看>>
Android源代码下载编译
查看>>
jsp---语句对象Statement
查看>>
RESTful API
查看>>
前端UI框架总结
查看>>
Atom 初识
查看>>
通向架构师的道路(第一天)之Apache整合Tomcat - lifetragedy的专栏 - 博客频道 - CSDN.NET...
查看>>
Javascript创建对象的7种模式
查看>>
Shell工作笔记01
查看>>
项目、软件开发过程中版本术语
查看>>
CSS实现背景透明,文字不透明(各浏览器兼容)
查看>>
【转】[大学引导]超级链接、字体颜色、音乐播放公式
查看>>
T-SQL中INSERT、UPDATE
查看>>
Linux下Nginx服务器配置Modsecurity实现Web应用防护系统
查看>>