您的位置:首页 > 其它

V - How Many Zeroes? (数位dp)

2017-11-07 23:17 423 查看


V - How Many Zeroes?

 

题意:

求任意区间的数中0的出现次数

思路:

数位dp,注意判断是否是前导0 注意用长整型

代码:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
int bit[20];
ll dp[20][20];

ll dfs(int pos,int sum,int zero,int limit){//zero前导0,sum是0的个数
if(pos<0)
return zero?1:sum;
if(!zero&&!limit&& dp[pos][sum] != -1) return dp[pos][sum];
int up=limit?bit[pos] : 9;

ll ans = 0;
for(int i=0; i<=up; i++){

if(zero&&!i) ans+=dfs(pos-1,0,1,limit&&up==i);//判断前导零

else if(!i) ans+=dfs(pos-1,sum+1,0,limit&&i ==up);//第二次访问加1

else ans+=dfs(pos-1,sum,0,limit&&i==up);
}
if(!zero&&!limit) dp[pos][sum] = ans;
return ans;
}
ll cal(ll x){
if(x<0)return 0;
if(x== 0) return 1;
memset(dp,-1,sizeof(dp));
int pos=0;
while(x){
bit[pos++] = x%10;
x/=10;
}
return dfs(pos-1,0,1,1);
}
int main()
{
int T,ans=1;
ll n,m;
scanf("%d",&T);
while(T--){
scanf("%lld %lld",&n,&m);
printf("Case %d: %lld\n",ans++,cal(m) - cal(n-1));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数位dp ACM 算法 dp dfs