首页 > 其他 > 详细

UVA1152-4 Values whose Sum is 0(分块)

时间:2018-09-09 00:26:16      阅读:257      评论:0      收藏:0      [点我收藏+]
Problem UVA1152-4 Values whose Sum is 0

Accept: 794  Submit: 10087
Time Limit: 9000 mSec

技术分享图片 Problem Description

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 ?rst line of the input ?le 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 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

 

题解:这个题主要是太陈了,觉得是个大水题,但是第一次见的时候不是太容易想。思想很深刻,分块,明明都是暴力枚举,但即便不加二分查找这个方法也在数量级上碾压四重for循环,感觉上有一点不可思议,想想莫队算法是不是也利用了这个思想(分块真的可以出奇迹)。

 

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 const int maxn = 4000 + 10;
 6 
 7 int a[maxn], b[maxn], c[maxn], d[maxn];
 8 int sum[maxn*maxn];
 9 int n;
10 
11 int main()
12 {
13     //freopen("input.txt", "r", stdin);
14     int iCase;
15     scanf("%d", &iCase);
16     while (iCase--) {
17         scanf("%d", &n);
18         for (int i = 0; i < n; i++) {
19             scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
20         }
21 
22         int cnt = 0;
23         for (int i = 0; i < n; i++) {
24             for (int j = 0; j < n; j++) {
25                 sum[cnt++] = a[i] + b[j];
26             }
27         }
28         sort(sum, sum + cnt);
29         long long ans = 0;
30         for (int i = 0; i < n; i++) {
31             for (int j = 0; j < n; j++) {
32                 ans += upper_bound(sum, sum + cnt, -c[i] - d[j]) - lower_bound(sum, sum + cnt, -c[i] - d[j]);
33             }
34         }
35 
36         printf("%lld\n", ans);
37         if (iCase) printf("\n");
38     }
39     return 0;
40 }

 

UVA1152-4 Values whose Sum is 0(分块)

原文:https://www.cnblogs.com/npugen/p/9611070.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!