bzoj 1026 windy数(数位dp入门题)

题目链接 题意:不含前导零且相邻两个数字之差至少为2的正整数被称为windy数。 windy想知道,在A和B之间,包括A和B,总共有多少个windy数? 思路:数位dp 这道题的特点是前面不允许前导0,也就是说,如果第i位前面全是0的话,这个数就变成了i位数,i就变成了最高位,而最高位没有前面的数(**如果这里不考虑不允许前导0这个因素而把前面的一个数认为成是0就错了) **最高位的数可以直接取。 还有记忆化调用以及存储的时候也要注意…只有当位数相同的时候转移才有意义。 具体的方法是dfs中多了一个prehasnonzero的bool变量,就是字面意思,判断当前位置前面的位置是够存在一个非0的值。

  1/* ***********************************************
  2Author :111qqz
  3Created Time :2016年03月15日 星期二 19时49分57秒
  4File Name :code/bzoj/1026.cpp
  5************************************************ */
  6
  7#include <cstdio>
  8#include <cstring>
  9#include <iostream>
 10#include <algorithm>
 11#include <vector>
 12#include <queue>
 13#include <set>
 14#include <map>
 15#include <string>
 16#include <cmath>
 17#include <cstdlib>
 18#include <ctime>
 19#define fst first
 20#define sec second
 21#define lson l,m,rt<<1
 22#define rson m+1,r,rt<<1|1
 23#define ms(a,x) memset(a,x,sizeof(a))
 24typedef long long LL;
 25#define pi pair < int ,int >
 26#define MP make_pair
 27
 28using namespace std;
 29const double eps = 1E-8;
 30const int dx4[4]={1,0,0,-1};
 31const int dy4[4]={0,-1,1,0};
 32const int inf = 0x3f3f3f3f;
 33int l,r;
 34int dp[30][10];  
 35int digit[30];
 36
 37
 38int dfs ( int pos,int pre,bool limit,bool prehasnonzero) // prehasnonzero表示当前位前面的位是否有非0的位。
 39{zhi
 40    if (pos==0) return 1;
 41    if (prehasnonzero&&!limit&&dp[pos][pre]!=-1) return dp[pos][pre];  //位数相同才通用,所以prehasnonzero为true才调用
 42
 43    int mx = limit?digit[pos]:9;
 44
 45    int res = 0 ;
 46
 47    if (!prehasnonzero)
 48    {
 49	for ( int i =  0 ; i <= mx ; i++ )
 50	{
 51	    res+=dfs (pos-1,i,limit&&i==mx,i==0?false:true);
 52	}
 53    }
 54    else
 55    {
 56	for ( int i = 0 ; i <= mx ; i++)
 57	{
 58	    if (abs(i-pre)>=2)
 59	    {
 60		res+=dfs(pos-1,i,limit&&i==mx,true);
 61	    }
 62	}
 63    }
 64
 65
 66    if (prehasnonzero&&!limit)  dp[pos][pre] = res; //位数相同才通用,所以prehasnonzero为true时才记录。
 67    return res;
 68}
 69int solve ( int  n )
 70{
 71    ms(digit,0);
 72
 73    int len = 0  ;
 74
 75    while (n)
 76    {
 77	digit[++len] = n;
 78	n/=10;
 79    }
 80    return dfs(len,0,true,0);  //pre的初始值应该是0而不是-1,因为不允许前导0,位数是可变的。..所以不过是一种特殊情况而已。
 81}
 82int main()
 83{
 84	#ifndef  ONLINE_JUDGE 
 85	freopen("code/in.txt","r",stdin);
 86  #endif
 87
 88	ios::sync_with_stdio(false);
 89	ms(dp,-1);
 90	cin>>l>>r;
 91	int ans = 0 ;
 92	ans += solve (r)-solve(l-1);
 93//	cout<<solve(15)<<endl;
 94	cout<<ans<<endl;
 95
 96
 97  #ifndef ONLINE_JUDGE  
 98  fclose(stdin);
 99  #endif
100    return 0;
101}