题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2381
题意就是给出5000个数, 求有多少组a + b = c, 一开始只想到了n ^ 2 * log(n)的做法, T了之后果断改成了n ^ 2就过了,速度也不慢。。。
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <ctime>
using namespace std;
typedef long long LL;
const int N = 5050;
int n, m;
LL A[N], C[N], B[N];
inline LL c2(LL n) {
return n * (n - 1) / 2;
}
LL gao() {
LL res = 0LL;
sort(A, A + n);
m = 1;
B[0] = A[0];
C[0] = 1;
for (int i = 1; i < n; i++) {
if (A[i] == B[m - 1])
C[m - 1]++;
else {
B[m] = A[i];
C[m] = 1;
m++;
}
}
for (int i = 0; i < m - 1; i++) {
int j, k;
if (C[i] > 1) {
k = lower_bound(B, B + m, B[i] * 2) - B;
if (k < m && B[k] == B[i] * 2)
res += c2(C[i]) * C[k];
}
if (i == m - 2) break;
j = i + 1;
k = lower_bound(B, B + m, B[i] + B[j]) - B;
if (k == m) return res;
if (B[k] == B[i] + B[j]) {
res += C[i] * C[j] * C[k];
k++;
}
for (; k < m; k++) {
while (j < k && B[i] + B[j] < B[k]) j++;
if (j == k) continue;
if (B[i] + B[j] == B[k]) {
res += C[i] * C[j] * C[k];
}
}
}
return res;
}
int main() {
while (~scanf("%d", &n)) {
for (int i = 0; i < n; i++) {
scanf("%lld", A + i);
}
printf("%lld\n", gao());
}
return 0;
}