您的位置:首页 > 其它

hdu 3555(数位dp裸题)

2014-03-07 00:04 169 查看
题意:求1-n中有多少个数含有49;

解法:应该是数位dp最简单的题目了吧。学了dfs版的写法,第一次自己敲了出来,几乎是在默写,感觉还不熟练。dp[pos][pre][flag] 表示在后pos位,第pos+1位的数字为pre,前面是否出现49的标记为flag(1为出现过, 0 为未出现过)的数字个数。dfs的细节要自己体会,还要多敲多练;

代码:
/****************************************************
* author:xiefubao
*******************************************************/
#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <string.h>

using namespace std;

#define eps 1e-8
typedef long long LL;

LL dp[30][10][2];
char s[30];
LL dfs(int pos,int pre,bool flag,bool limit)
{
if(pos==-1) return flag==1;
if(!limit&&dp[pos][pre][flag]!=-1)
return dp[pos][pre][flag];
int end=limit? s[pos] : 9;
LL ans=0;
for(int i=0;i<=end;i++){
if(pre==4&&i==9) ans+=dfs(pos-1,i,1,limit&&i==end);
else ans+=dfs(pos-1,i,flag,limit&&i==end);
}
if(!limit) dp[pos][pre][flag]=ans;
return ans;
}
LL compute(LL t)
{
int p=0;
while(t)
{
s[p++]=t%10;
t/=10;
}
return dfs(p-1,0,0,1);
}

int main()
{
LL t;int n;cin>>n;
while(n--)
{
cin>>t;
memset(dp,-1,sizeof dp);
cout<<compute(t)<<'\n';
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: