bzoj 1026 windy数(数位dp入门题)
题目链接 题意:不含前导零且相邻两个数字之差至少为2的正整数被称为windy数。 windy想知道,在A和B之间,包括A和B,总共有多少个windy数? 思路:数位dp 这道题的特点是前面不允许前导0,也就是说,如果第i位前面全是0的话,这个数就变成了i位数,i就变成了最高位,而最高位没有前面的数(**如果这里不考虑不允许前导0这个因素而把前面的一个数认为成是0就错了) **最高位的数可以直接取。 还有记忆化调用以及存储的时候也要注意...只有当位数相同的时候转移才有意义。 具体的方法是dfs中多了一个prehasnonzero的bool变量,就是字面意思,判断当前位置前面的位置是够存在一个非0的值。
/* ***********************************************
Author :111qqz
Created Time :2016年03月15日 星期二 19时49分57秒
File Name :code/bzoj/1026.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6int l,r;
7int dp[30][10];
8int digit[30];
1int dfs ( int pos,int pre,bool limit,bool prehasnonzero) // prehasnonzero表示当前位前面的位是否有非0的位。
2{zhi
3 if (pos==0) return 1;
4 if (prehasnonzero&&!limit&&dp[pos][pre]!=-1) return dp[pos][pre]; //位数相同才通用,所以prehasnonzero为true才调用
int mx = limit?digit[pos]:9;
int res = 0 ;
1 if (!prehasnonzero)
2 {
3 for ( int i = 0 ; i <= mx ; i++ )
4 {
5 res+=dfs (pos-1,i,limit&&i==mx,i==0?false:true);
6 }
7 }
8 else
9 {
10 for ( int i = 0 ; i <= mx ; i++)
11 {
12 if (abs(i-pre)>=2)
13 {
14 res+=dfs(pos-1,i,limit&&i==mx,true);
15 }
16 }
17 }
1 if (prehasnonzero&&!limit) dp[pos][pre] = res; //位数相同才通用,所以prehasnonzero为true时才记录。
2 return res;
3}
4int solve ( int n )
5{
6 ms(digit,0);
int len = 0 ;
1 while (n)
2 {
3 digit[++len] = n;
4 n/=10;
5 }
6 return dfs(len,0,true,0); //pre的初始值应该是0而不是-1,因为不允许前导0,位数是可变的。..所以不过是一种特殊情况而已。
7}
8int main()
9{
10 #ifndef ONLINE_JUDGE
11 freopen("code/in.txt","r",stdin);
12 #endif
1 ios::sync_with_stdio(false);
2 ms(dp,-1);
3 cin>>l>>r;
4 int ans = 0 ;
5 ans += solve (r)-solve(l-1);
6// cout<<solve(15)<<endl;
7 cout<<ans<<endl;
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}