POJ 2785 4 Values whose Sum is 0(hash表)
2015-08-29 08:26
597 查看
Description
给出四个数列,现从每个数列中选取一个数,问有多少中可能使这四个数和为0
Input
第一行为数列长度,之后n行每行4个整数分别表示四个数列中对应位置的值
Output
输出4个数和为0的可能数
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
Solution
用前两列的和维护一个hash,然后用第三第四列的和的相反数去hash里面找即可
Code
给出四个数列,现从每个数列中选取一个数,问有多少中可能使这四个数和为0
Input
第一行为数列长度,之后n行每行4个整数分别表示四个数列中对应位置的值
Output
输出4个数和为0的可能数
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
Solution
用前两列的和维护一个hash,然后用第三第四列的和的相反数去hash里面找即可
Code
#include<cstdio> #include<cstring> #include<cmath> #include<iostream> #include<algorithm> #include<functional> #include<queue> using namespace std; #define maxn 4001 int n; int a[maxn],b[maxn],c[maxn],d[maxn]; int cd[maxn*maxn]; int cmp(const void*a,const void*b) { return *(int*)a-*(int*)b; } int main() { scanf("%d",&n); int i,j; for(i=0;i<n;i++) scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]); for(i=0;i<n;i++)//用前两列的和维护hash表 for(j=0;j<n;j++) cd[i*n+j]=c[i]+d[j]; qsort(cd,n*n,sizeof(int),cmp);//对hash表排序 long long res=0; for(i=0;i<n;i++) for(j=0;j<n;j++) { int t=-(a[i]+b[j]);//在hash表中查找三四列和的相反数 res+=upper_bound(cd,cd+n*n,t)-lower_bound(cd,cd+n*n,t); } printf("%lld\n",res); return 0; }
相关文章推荐
- 从数据库中提取到ueditor并且重新编辑
- POJ 2664 && HDU 1144 Prerequisites?(水~)
- 【LeetCode-面试算法经典-Java实现】【225-Implement Stack using Queues(用队列实现栈操作)】
- 6、iOS 开发之 UIPickerView
- 4、iOS 开发之 UITableView
- 3、iOS 开发之 UIScrollView UIPageController NSTimer
- iOS部分-UI基础控件 - 01天 入门 第11课 上下左右移动
- 新建Android工程报错:'Building workspace' has encountered a problem...解决办法
- ngui自适应的一点学习
- ios开发-UI-自定义Tabbar 图书布局
- iOS之Operation Queues 和 Grand Central Dispatch
- PHP生成UUID
- .NET 的 Debug 和 Release build 对执行速度的影响
- 关于CodeFirst异常:无法确定类型'XXX'和类型‘YYY’之间的关联的主体端,必须使用关系 Fluent API 或数据注释显式配置此关联的主体端。
- 【我们都爱Paul Hegarty】斯坦福IOS8公开课个人笔记44 Popover Segue
- Android UI设计:Notification
- Android UI设计:PopupWindow
- MongoVUE对json数据的导入和导出
- Unable to run Vmware workstation 11 - failed to build vmnet
- [leetcode-187]Repeated DNA Sequences(java)