【YBTOJ】【Luogu P6218】[USACO06NOV] Round Numbers S
【YBTOJ】【Luogu P6218】[USACO06NOV] Round Numbers S
链接:
题目大意:
在 \([l,r]\) 中找到二进制中零数大于等于一数的数的个数。
正文:
数位 DP 板子题。设 \(f_{len,A,B,pos}\) 表示当前 \(len\) 位 \(A\) 个零、\(B\) 个一,碰没碰顶的方案数。
代码:
const int N = 60;
inline ll Read()
{
ll x = 0, f = 1;
char c = getchar();
while (c != '-' && (c < '0' || c > '9')) c = getchar();
if (c == '-') f = -f, c = getchar();
while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
return x * f;
}
ll l, r;
int a[N], Len;
ll f[N][N][N][2];
ll DP (int len, int A, int B, bool pos)
{
if (~f[len][A][B][pos]) return f[len][A][B][pos];
if (!len) return A >= B;
int m = pos? a[len]: 1;
ll ans = 0;
for (int i = 0; i <= m; i++)
ans += DP(len - 1, (B > 0) * (A + (i == 0)), B + (i == 1), pos && i == m);
return f[len][A][B][pos] = ans;
}
ll Solve (ll n)
{
if (!n) return 1;
Len = 0;
memset (a, 0, sizeof a);
for (ll m = n; m; m /= 2)
a[++Len] = m % 2;
ll ans = 0;
for (int i = 0; i <= a[Len]; i++)
ans += DP(Len - 1, 0, i == 1, i == a[Len]);
return ans;
}
int main()
{
l = Read(), r = Read();
memset (f, -1, sizeof f);
printf ("%lld\n", Solve(r) - Solve(l - 1));
return 0;
}