问题其实是求等比数列并集 与等差数列并集 的交集 ,后文会把 略去但默认加上
等比数列
等比数列除了 或 或 只有 个数,其它也均为指数增长
所以可以先用的等比数列结合哈希表暴力枚举得到
等差数列
故每次求出 后令 ,可以让下一次求交集更加迅速
求 有两种方式,一种是遍历 判断其中元素是否在 ,另一种是遍历 判断其中元素是否在
选择 中较小的来进行遍历,类似启发式合并 ,而输入保证的 递减 ,这整体而言会造成 逐渐变小,所以只需要找到一个临界值或者附近的分开两种合并方式即可
代码
#include <iostream>
#include <unordered_set>
using namespace std;
int ceil_div(int a, int b) {
if (b < 0) a = -a, b = -b;
return a >= 0 ? (a + b - 1) / b : a / b;
}
int floor_div(int a, int b) {
if (b < 0) a = -a, b = -b;
return a >= 0 ? a / b : (a - b + 1) / b;
}
void P1(int l, int r, int x, int y, unordered_set<int>& W, unordered_set<int>& WandZ) {
if ((y > 0 && x + y > r) || (y < 0 && x + y < l)) return;
if (x + y > r) for (int z = ceil_div(r - x, y) * y + x; l <= z; z += y) {
if (W.count(z)) {
WandZ.insert(z);
W.erase(z);
}
}
else if (x + y < l) for (int z = ceil_div(l - x, y) * y + x; z <= r; z += y) {
if (W.count(z)) {
WandZ.insert(z);
W.erase(z);
}
}
else for (int z = x + y; l <= z && z <= r; z += y) {
if (W.count(z)) {
WandZ.insert(z);
W.erase(z);
}
}
}
void P2(int l, int r, int x, int y, unordered_set<int>& W, unordered_set<int>& WandZ) {
if ((y > 0 && x + y > r) || (y < 0 && x + y < l)) return;
for (auto w = W.begin(); w != W.end();) {
if ((*w - x) % y == 0 && (*w - x) / y > 0) {
WandZ.insert(*w);
w = W.erase(w);
}
else ++w;
}
}
void P3(int l, int r, int x, unordered_set<int>& W, unordered_set<int>& WandZ) {
if (l <= x && x <= r && W.count(x) && !WandZ.count(x)) {
WandZ.insert(x);
W.erase(x);
}
}
int main() {
short t;
scanf("%hd", &t);
for (; t--;) {
int n, m, l, r;
scanf("%d%d%d%d", &n, &m, &l, &r);
unordered_set<int> W;
for (; n--;) {
long long p, q;
scanf("%lld%lld", &p, &q);
if (q == 1) {
if (l <= p && p <= r) W.insert((int)p);
}
else if (q == -1) {
if (l <= p && p <= r) W.insert((int)p);
if (l <= -p && -p <= r) W.insert((int)-p);
}
else if (p * q == 0) {
if (l <= 0 && 0 <= r) W.insert(0);
}
else {
for (long long w = p * q; -100000000 <= w && w <= 100000000; w *= q)
if (l <= w && w <= r) W.insert((int)w);
}
}
unordered_set<int> WandZ;
for (;m--;) {
int x, y;
scanf("%d%d", &x, &y);
if (y == 0) {
P3(l, r, x, W, WandZ);
break;
}
if (y == 0 || y > 0 && W.size() <= max(floor_div(r - x, y), 0) - max(ceil_div(l - x, y), 0) + 1 || y < 0 && W.size() <= max(floor_div(l - x, y), 0) - max(ceil_div(r - x, y), 0) + 1) {
P2(l, r, x, y, W, WandZ);
break;
}
P1(l, r, x, y, W, WandZ);
}
if (m >= 0) for (;m--;) {
int x, y;
scanf("%d%d", &x, &y);
if (y == 0) {
P3(l, r, x, W, WandZ);
break;
}
P2(l, r, x, y, W, WandZ);
}
if (m >= 0) for (;m--;) {
int x, y;
scanf("%d%d", &x, &y);
P3(l, r, x, W, WandZ);
}
printf("%zu\n", WandZ.size());
}
}