Skip to content

Instantly share code, notes, and snippets.

@splitline
Created October 10, 2018 17:23
Show Gist options
  • Save splitline/d851f5cb17aace59a1cff557774f7fcb to your computer and use it in GitHub Desktop.
Save splitline/d851f5cb17aace59a1cff557774f7fcb to your computer and use it in GitHub Desktop.
#include <cstdio>
// #include <unordered_map>
#include <algorithm>
#include <vector>
char _getchar()
{
static char buf[1000000], *p1 = buf, *p2 = buf;
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin), p1 == p2) ? EOF : *p1++;
}
void get_int(int* u)
{
static char c;
while ((c = _getchar()) < '0') if (c == EOF) return;
*u = c - '0';
while ((c = _getchar()) >= '0') *u = (*u << 3) + (*u << 1) + (c ^ '0');
}
int count[100001] = { 0 };
int main()
{
int n, m;
get_int(&n);
int stones[n], max = -1;
for (int i = 0; i < n; ++i) {
get_int(&stones[i]);
++count[stones[i]];
if (stones[i] > max) max = stones[i];
}
max *= 2;
std::sort(stones, stones + n);
std::vector<int> stones_unique;
int pre_value = -1;
for(int i=0;i<n;i++){
if(stones[i]!=pre_value) {
stones_unique.push_back(stones[i]);
pre_value = stones[i];
}
}
get_int(&m);
do {
int sum;
get_int(&sum);
if (sum > max) {
printf("0 ");
continue;
}
long long answer = 0;
for (int i = 0; i < stones_unique.size(); ++i) {
if(stones_unique[i] > sum/2) break;
int complement = sum - stones_unique[i];
// if(complement < 0) break;
if(complement == stones_unique[i]) // C(n, 2)
answer += (count[complement] * (count[complement] - 1))/2;
else // C(n, 1) * C(m, 1)
answer += count[stones_unique[i]] * count[complement];
}
printf("%lld ", answer );
} while(--m);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment