Home BOJ. Four Numbers Of With Sum (7453)
Post
Cancel

BOJ. Four Numbers Of With Sum (7453)

[Link] https://www.acmicpc.net/problem/7453


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstring>
// #include <bits/stdc++.h>
using namespace std;
#define for0(i, n) for(int i = 0; i < n; i++)
#define for1(i, n) for(int i = 1; i < n; i++)
#define fori(s, e) for(int i = s; i < e; i++)
#define ll long long
#define endl "\n"
#define nulls '\0'
#define dkdk " "

const int MAX = 5e5 + 1;
int n;
vector<int> a, b, c, d;
int main() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  cin >> n;
  a.resize(n);
  b.resize(n);
  c.resize(n);
  d.resize(n);
  for0(i, n) cin >> a[i] >> b[i] >> c[i] >> d[i];
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  sort(c.begin(), c.end());
  sort(d.begin(), d.end());
  vector<int> ab, cd;
  for0(i, n) {
    for0(j, n) {
      ab.push_back(a[i] + b[j]);
      cd.push_back(c[i] + d[j]);
    }
  }
  sort(ab.begin(), ab.end());
  sort(cd.begin(), cd.end());
  int ab_idx = 0, cd_idx = cd.size() - 1;
  ll cnt = 0;

  while(ab_idx < ab.size() && cd_idx >= 0) {
    int ab_val = ab[ab_idx], cd_val = cd[cd_idx];
    int sum = ab_val + cd_val;
    if(sum == 0) {
      int abcnt = 1, cdcnt = 1;
      while(ab_idx + 1 < ab.size() && ab[ab_idx + 1] == ab_val) { abcnt++; ab_idx++; }
      while(cd_idx - 1 >= 0 && cd[cd_idx - 1] == cd_val) { cdcnt++; cd_idx--; }
      cnt+=(ll)abcnt * cdcnt;
      ab_idx++; cd_idx--;
    } else if(sum > 0) cd_idx--;
    else ab_idx++;
  }

  cout << cnt;
  return 0;
}
This post is licensed under CC BY 4.0 by the author.