BZOJ1026 [SCOI2009]windy数 数位dp

欢迎访问~原文出处——博客园-zhouzhendong

去博客园看该题解


题目传送门 - BZOJ1026


 

题目概括

  求区间[A,B]中有多少数满足下面的条件。

  条件:该数相邻两位之差不小于2。


 

题解

  简单的数位dp。

  一个记忆化dfs就解决了。

  dp[i][j]表示剩余i位数,第i+1位为j的windy数总数。

  太简单了,不会的话自己看代码。


代码

 1 #include <cstring>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 #include <cmath>
 6 using namespace std;
 7 int A,B;
 8 int a[12],dp[12][10];
 9 int dfs(int d,int num,bool zero,bool full){
10     if (!zero&&!full&&dp[d][num]!=-1)
11         return dp[d][num];
12     if (!d)
13         return 1;
14     int top=full?a[d]:9;
15     int ans=0;
16     for (int i=0;i<=top;i++){
17         if (!zero&&abs(num-i)<2)
18             continue;
19         ans+=dfs(d-1,i,zero&&!i,full&&i==top);
20     }
21     if (!zero&&!full)
22         dp[d][num]=ans;
23     return ans;
24 }
25 int solve(int n){
26     if (!n)
27         return 1;
28     int d=0;
29     while (n)
30         a[++d]=n%10,n/=10;
31     return dfs(d,0,1,1);
32 }
33 int main(){
34     scanf("%d%d",&A,&B);
35     memset(dp,-1,sizeof dp);
36     printf("%d",solve(B)-solve(A-1));
37     return 0;
38 }

 

  

posted @ 2017-08-14 15:32  zzd233  阅读(202)  评论(0编辑  收藏  举报