UVa 1152 -4 Values whose Sum is 0—[哈希表实现]
2016-04-12 15:12
393 查看
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 × B × C × D are such that a + b + c + d = 0. In the following, we assume that all lists have the same size n. Input The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs. 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 228) that belong respectively to A, B, C and D. Output For each test case, your program has to write the number quadruplets whose sum is zero. The outputs of two consecutive cases will be separated by a blank line. Sample Input 1
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 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).
解题思路:
枚举并存储A+B的和,然后枚举C+D,搜索-C-D的个数,问题的关键是如何存储A+B的和。本题数据量不小,极限数据n=4000时,A+B的和有16,000,000个,数组显然开不下。那么不妨建立哈希表来存储。
代码如下:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <set> #include <vector> #include <ctime> #define H 1000000 #define maxn 4000 #define time__ cout<<" time: "<<double(clock())/CLOCKS_PER_SEC<<endl; using namespace std; vector<int> Hash2[H]; int A[maxn+5]; int B[maxn+5]; int C[maxn+5]; int D[maxn+5]; int n; inline void Hash_clear(){ for(int i=0;i<H;i++) Hash2[i].clear(); } inline int h(int x){ return abs(x%H); } inline int count_(int x){ int h_=h(x); int cnt=0; for(int i=0;i<Hash2[h_].size();i++) if(Hash2[h_][i]==x) cnt++; return cnt; } int main(int argc, const char * argv[]) { int T; scanf("%d",&T); while (T--) { Hash_clear(); int cnt=0; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]); for(int i=0;i<n;i++) for(int j=0;j<n;j++){ int x=A[i]+B[j]; Hash2[h(x)].push_back(x); } for(int i=0;i<n;i++) for(int j=0;j<n;j++){ int x=C[i]+D[j]; cnt+=count_(-x); } cout<<cnt<<endl; if(T) cout<<endl; } //time__; return 0; }
相关文章推荐
- Android UI-开源框架ImageLoader的完美例子
- android 事件处理机制之requestDisallowInterceptTouchEvent
- Jewel 版ceph安装和BlueStore配置
- Hbuild - 使用海马玩模拟器调试
- 如何输出类型为uint_16,uint_32,uint_64等类型的变量
- Android Uevent 分析,从kernel到framework
- iOS UILabel详解
- Java Blocking Queue
- burpsuite联合sqlmap扫描注入点
- ueditor插入flv视频
- iOS--UILabel上画横线
- iOS--UILabel上画横线
- Request.url请求路径的一些属性
- String与StringBuffer、StringBuilder的区别
- Android中sqlite之从网上获取数据更新UI
- 禁掉UITextField的粘贴功能
- topLayoutGuide
- UITabBarController简单的使用
- 关于 UITapGestureRecognizer 一些注意的地方
- iOS相机相册调用 — UIImagePickerController