1. 程式人生 > >poj2785 4 Values whose Sum is 0

poj2785 4 Values whose Sum is 0

style hose log namespace binary earch return 實現 sort

思路:
折半枚舉,二分。

實現:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 int a[4][4005];
 6 int buf[16000005];
 7 int main()
 8 {
 9     int n;
10     cin >> n;
11     for (int i = 0; i < n; i++)
12     {
13         for (int j = 0; j < 4; j++)
14 { 15 cin >> a[j][i]; 16 } 17 } 18 int cnt = 0; 19 for (int i = 0; i < n; i++) 20 { 21 for (int j = 0; j < n; j++) 22 { 23 buf[i * n + j] = a[0][i] + a[1][j]; 24 } 25 } 26 sort(buf, buf + n * n); 27 for
(int i = 0; i < n; i++) 28 { 29 for (int j = 0; j < n; j++) 30 { 31 int tmp = -a[2][i] - a[3][j]; 32 if (binary_search(buf, buf + n * n, tmp)) 33 { 34 int l = lower_bound(buf, buf + n * n, tmp) - buf; 35 int r = upper_bound(buf, buf + n * n, tmp) - buf;
36 cnt += r - l; 37 } 38 } 39 } 40 cout << cnt << endl; 41 return 0; 42 }

poj2785 4 Values whose Sum is 0