[USACO06NOV] Round Numbers S 题解
数位 dp 模版题,这里用记忆化搜索。
用两个变量(下面是 cnt1 和 cnt2)记录 $0$ 和 $1$ 的数量就行。
然后就做完了,时间复杂度 $O(\log_2^3 r)$。
#include<bits/stdc++.h>
using namespace std;
int l, r, a[205], f[205][205][205];
inline int dfs(int idx, int cnt0, int cnt1, bool limit, bool lead){
//cout << idx << ' ' << cnt0 << ' ' << cnt1 << ' ' << limit << ' ' << lead << endl;
if(idx == 0) return cnt0 >= cnt1;
if(f[idx][cnt0][cnt1] != -1 && !limit && !lead) return f[idx][cnt0][cnt1];
int res = dfs(idx - 1, cnt0 + !lead, cnt1, limit && !a[idx], lead);
if(a[idx] || !limit) res += dfs(idx - 1, cnt0, cnt1 + 1, limit, 0);
if(!limit && !lead) f[idx][cnt0][cnt1] = res;
return res;
}
inline int calc(int x){
if(x == 0) return 1;
int len = 0;
memset(f, -1, sizeof(f));
while(x) a[++len] = x & 1, x >>= 1;
return dfs(len, 0, 0, 1, 1);
}
signed main(){
cin >> l >> r;
cout << calc(r) - calc(l - 1) << endl;
return 0;
}

浙公网安备 33010602011771号