POJ2282 The Counting Problem(数位DP)
用dp[pos][val][cnt]表示状态,pos是数位,val是当前统计的数字,cnt是目前统计的目标数字的出现次数
注意状态的转移过程,统计数字0时前导0的影响。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 typedef long long LL; 6 int dig[15],pos; 7 LL dp[15][10][15],ans[2][10]; 8 9 LL dfs(int pos,int val,int cnt,bool lead,bool limit){ 10 if(pos==0) return cnt; 11 if(!limit&&!lead&&dp[pos][val][cnt]!=-1) return dp[pos][val][cnt]; 12 int len=limit?dig[pos]:9,t=0; 13 LL ans=0; 14 for(int i=0;i<=len;i++){ 15 if(val!=i) t=cnt; 16 else{ 17 if(lead&&val==0) t=0; 18 else t=cnt+1; 19 } 20 ans+=dfs(pos-1,val,t,lead&&i==0,limit&&i==len); 21 } 22 if(!limit&&!lead) dp[pos][val][cnt]=ans; 23 return ans; 24 } 25 26 void solve(LL x,int idx){ 27 if(x==0) return ; 28 int pos=0; 29 while(x){ 30 dig[++pos]=x%10; 31 x/=10; 32 } 33 for(int i=0;i<10;i++)//对每一个数字分别求解 34 ans[idx][i]=dfs(pos,i,0,1,1); 35 } 36 37 int main(){ 38 memset(dp,-1,sizeof(dp)); 39 LL a,b; 40 while(~scanf("%lld%lld",&a,&b),a+b){ 41 if(a>b) swap(a,b); 42 memset(ans,0,sizeof(ans)); 43 solve(a-1,0),solve(b,1); 44 for(int i=0;i<10;i++) 45 printf("%lld ",ans[1][i]-ans[0][i]); 46 printf("\n"); 47 } 48 return 0; 49 }