Alex_tz307

USACO 2020 January Contest, Gold Problem 2. Farmer John Solves 3SUM

Jun 1st, 2021 (edited)
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. using int64 = long long;
  5.  
  6. ifstream fin("threesum.in");
  7. ofstream fout("threesum.out");
  8.  
  9. const int MAXN = 5e3;
  10. const int MAXV = 2e6 + 1;
  11. const int offset = 1e6;
  12. int a[MAXN], freq[MAXV];
  13. int64 sol[MAXN][MAXN];
  14.  
  15. int main() {
  16.   int n, Q;
  17.   fin >> n >> Q;
  18.   for (int i = 0; i < n; ++i)
  19.     fin >> a[i];
  20.   for (int i = 0; i < n - 2; ++i) {
  21.     for (int j = i + 1; j < n; ++j) {
  22.       int sum = -a[i] - a[j] + offset;
  23.       if (0 <= sum && sum < MAXV)
  24.         sol[i][j] = freq[sum];
  25.       ++freq[a[j] + offset];
  26.     }
  27.     for (int j = i + 1; j < n; ++j)
  28.       --freq[a[j] + offset];
  29.   }
  30.   for (int i = n - 3; i >= 0; --i)
  31.     for (int j = i + 2; j < n; ++j)
  32.       sol[i][j] += sol[i][j - 1] + sol[i + 1][j] - sol[i + 1][j - 1];
  33.   for (int q = 0; q < Q; ++q) {
  34.     int l, r;
  35.     fin >> l >> r;
  36.     fout << sol[l - 1][r - 1] << '\n';
  37.   }
  38.   fin.close();
  39.   fout.close();
  40.   return 0;
  41. }
  42.  
Add Comment
Please, Sign In to add comment