NC222463. [USACOJan20G]FarmerJohnSolves3SUM
描述
输入描述
The first line contains two space-separated integers N and Q. The second line contains the space-separated elements A1,…,AN of array A. Each of the subsequent Q lines contains two space-separated integers ai and bi, representing a query.
It is guaranteed that −106≤Ai≤106 for every array element Ai.
输出描述
The output should consist of Q lines, with each line i containing a single integer---the answer to the i-th query. Note that you should use 64-bit integers to avoid overflow.
示例1
输入:
7 3 2 0 -1 1 -2 3 3 1 5 2 4 1 7
输出:
2 1 4
说明:
For the first query, the possible triples are (A1,A2,A5) and (A2,A3,A4).C++(clang++ 11.0.1) 解法, 执行用时: 727ms, 内存消耗: 124816K, 提交时间: 2023-06-10 17:24:53
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ll; const int maxN = 5e3 + 10, INF = 1e6; int n, Q, a[maxN], sum[INF + INF]; ll d[maxN][maxN]; int main(){ cin >> n >> Q; for(int i = 1; i <= n; i++){ cin >> a[i]; a[i] += INF; } for(int i = 1; i <= n; i++){ sum[a[i + 1]]++; for(int j = i + 2; j <= n; j++){ if(a[i] + a[j] >= INF && a[i] + a[j] <= 3 * INF) d[i][j] = sum[3 * INF - a[i] - a[j]]; sum[a[j]]++; } for(int j = i + 1; j <= n; j++) sum[a[j]]--; } for(int k = 4; k <= n; k++) for(int i = 1; i + k - 1 <= n; i++){ int j = i + k - 1; d[i][j] += d[i][j - 1] + d[i + 1][j] - d[i + 1][j - 1]; } while(Q--){ int x, y; cin >> x >> y; cout << d[x][y] << endl; } return 0; }