P5342 [TJOI2019]甲苯先生的线段树
#include
using namespace std;
#define ll long long
template <class t>
inline void read(t & res)
{
char ch;
while (ch = getchar(), !isdigit(ch));
res = ch ^ 48;
while (ch = getchar(), isdigit(ch))
res = res * 10 + (ch ^ 48);
}
template <class t>
inline void print(t x)
{
if (x > 9) print(x / 10);
putchar(x % 10 + 48);
}
const int e = 205;
ll f[e][e][2], ans;
bool a1[e], b1[e];
inline ll dp(int a, int b, ll s, int c)
{
int i, j, t, x, y, bit = max(max(a - 1, b), (int)log2(s) + 1) + 1;
bool flag = a == 3 && b == 2;
for (i = 0; i < bit; i++)
for (j = 0; j <= c; j++)
f[i][j][0] = f[i][j][1] = 0;
i = 0;
for (x = 0; x <= 1; x++)
for (y = 0; y <= 1; y++)
{
int k = x + y >> 1, z = x + y & 1;
if (i == b - 1 && !y) continue;
if (z != (s & 1)) continue;
if (i > b - 1 && y) continue;
if (i > a - 2 && x) continue;
f[0][x + y][k]++;
}
for (i = 0; i < bit - 1; i++)
{
ll d = s & (1ll << i + 1);
if (d) d = 1;
for (j = 0; j <= c; j++)
for (t = 0; t <= 1; t++)
if (f[i][j][t])
for (x = 0; x <= 1; x++)
for (y = 0; y <= 1; y++)
{
int now = x + y + t, k = now >> 1, z = now & 1;
if (i + 1 == b - 1 && !y) continue;
if (z != d) continue;
if (i + 1 > b - 1 && y) continue;
if (i + 1 > a - 2 && x) continue;
f[i + 1][j + x + y][k] += f[i][j][t];
}
}
return f[bit - 1][c][0];
}
inline ll calc(ll x)
{
ll res = x << 1;
while (x) res -= x & 1, x >>= 1;
return res;
}
int main()
{
int i, lx, ly, op, tst, h;
ll x, y, z;
read(tst);
while (tst--)
{
read(h); read(x); read(y); read(op);
ll x2 = x, y2 = y;
lx = ly = z = 0;
while (x) a1[++lx] = x & 1, x >>= 1;
while (y) b1[++ly] = y & 1, y >>= 1;
reverse(a1 + 1, a1 + lx + 1);
reverse(b1 + 1, b1 + ly + 1);
for (i = 1; i <= lx && i <= ly; i++)
if (a1[i] == b1[i]) z = z * 2 + a1[i];
else break;
ll s = calc(x2) + calc(y2) - calc(z) - calc(z >> 1);
if (op == 1)
{
print(s);
putchar('\n');
continue;
}
ans = 0;
for (int a = 0; a < h; a++)
for (int b = 0; b < h; b++)
{
ll y = ((1ll << a + 1) + (1ll << b + 1) - 3), x = s / y;
if (!x) continue;
if ((int)log2(x) + 1 + max(a, b) > h) continue;
ll k = s - x * y;
for (int c = 0; c <= a + b; c++)
if ((k + c) % 2 == 0) ans += dp(a, b, k + c >> 1, c);
}
print(ans - 1);
putchar('\n');
}
return 0;
}