您的位置:首页 > 其它

codeforces 855E 数位DP

2017-09-25 11:56 393 查看
简略题意:每次询问[Li,Ri]在b进制下每种0 到 b−1的数的个数都为偶数的个数,不包含前导0。

典型的数位DP套路题,最多十个进制,对每个进制暴力进行数位DP。

考虑构造状态dp[bit][pos][sta][st],代表当前处理bit进制时,处理到第pos个位置,状态为sta,是否已经没有前导0。

对于每个状态我们只需要记录每个数出现的次数即可,因为只有最多10位,且只需要知道其出现次数是不是偶数次。因此可以状压一下。若所有数出现为偶数次,则根据亦或的性质可以知道其最终结果为0。

因此我们需要计数的是,最终结果为0,且没有前导0的状态。

时间复杂度O(logn∗logn∗210∗2∗10)。

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

LL dig[66];
LL dp[13][66][2050][2];

LL dfs(LL t, LL pos, LL val, LL us, LL f) {
if(pos < 0) {
return val == 0 && us;
}
if(!f && dp[t][pos][val][us]!=-1)
return dp[t][pos][val][us];
LL tail, res= 0;
if(f) tail = dig[pos];
else tail = t - 1;
for(LL d = 0; d <= tail; d++) {
res += dfs(t, pos-1, (us||(d>0))?(val ^ (1<<d)):val, us || d > 0, f && d == tail);
}
if(!f)
dp[t][pos][val][us] = res;
return res;
}

LL solve(LL t, LL x) {
memset(dig, 0, sizeof dig);
LL cnt = 0;
while(x) {
dig[cnt++] = x % t;
x /= t;
};
return dfs(t, cnt-1, 0, 0, 1);
}

int main(){
memset(dp,-1,sizeof dp);
LL t;
scanf("%d", &t);
while(t--) {
LL x, y, z;
scanf("%lld%lld%lld", &x, &y, &z);
printf("%lld\n", solve(x, z) - solve(x, y-1));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: