POJ 2785 (二分)
2016-02-17 20:12
381 查看
4 Values whose Sum is 0
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 228 ) 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). Source Southwestern Europe 2005 |
先取两组记录两两的和,然后枚举另外两组两两的和从已知的和里面去找。
可能map常数比较大过不了,二分就可以了。
#include <iostream> #include <cmath> #include <cstdlib> #include <time.h> #include <vector> #include <cstdio> #include <cstring> #include <map> #include <algorithm> using namespace std; #define maxn 4111 int n; long long a[maxn][4]; long long sum[maxn*maxn]; int main () { while (scanf ("%d", &n) == 1) { for (int i = 1; i <= n; i++) { scanf ("%lld%lld%lld%lld", &a[i][0], &a[i][1], &a[i][2], &a[i][3]); } int cnt = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { long long num = a[i][2]+a[j][3]; sum[cnt++] = num; } } long long ans = 0; sort (sum, sum+cnt); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { long long num = -1 * (a[i][0] + a[j][1]); ans += upper_bound (sum, sum+cnt, num) - lower_bound (sum, sum+cnt, num); } } printf ("%lld\n", ans); } return 0; }
相关文章推荐
- (4) linux shell 命令 -- mkdir
- ubuntu15.0 编译SRS2.0
- Linux 解压压缩命令
- 有int d; int *d; bool d; double d;判断这个四个变量是否等于0?
- PHP的CI框架集成Smarty的最佳方式
- 【tyvj1860】后缀数组
- 南阳题目11-奇偶数分离
- 使用Echarts过程中遇到的问题
- EventBus使用详解(二)——EventBus使用进阶
- Dijkstra和Prim算法 【含数学证明】
- [置顶] Linux线程退出方式总结
- 集合
- OAuth2.0 Authorization flows and grant types
- thinkphp集成支付宝支付接口遇到的错误
- 2016上半年科研日志
- 使用SDWebImage下载图片,sharedDownloader方法下载成功,new 方法下载失败
- [ linux ] pad远程
- LoadRunner使用记录
- 2016再度起航
- 世界制造三巨头,谁是核心?