hdu_2089(数位dp)
标签: dp
我初次接触数位dp表面上看上去挺简单,但是仔细学还是要考虑很多细节的。wa了无数次,这里引入一个
很好地博客
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
ll dp[11][11];
void init()
{
dp[0][0] = 1;
for(int i = 1; i < 7; i++){
for(int j = 0; j <= 9; j++){
if(j==4) continue;
for(int k = 0; k <= 9; k++){
if(k!=4&&!(j==6&&k==2)){
dp[i][j] += dp[i-1][k];
}
}
}
}
}
int a[10];
ll solve(int n){
ll ans = 0;
int len = 0;
while(n){
a[len++] = n%10;
n = n/10;
}
int last = 0;
a[len] = 0;//防止特判只有一位的情况
for(int i = len-1; i >= 0; i--){
for(int j = 0; j < a[i]; j++){
/* if(j!=4 && !(j==2&&last==6)){
ans += dp[i+1][j];
}
*/
if(j==4 || (last==6 && j == 2))continue;
ans += dp[i+1][j];
}
if(a[i]==4 || (a[i]==2&&last==6)) break;
last = a[i];
}
return ans;
}
int main()
{
init();
ll n,m;
while(~scanf("%I64d %I64d",&n,&m))
{
if(m==0&&n==0) return 0;
ll ans = solve(m+1)-solve(n);
printf("%I64d
",ans);
}
return 0;
}
hdu_3555(数位dp)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
int a[30];
ll dp[30][3];
void init()
{
dp[0][0] = 1;
dp[0][1] = dp[0][2] = 0;
for(int i = 1; i < 30; i++)
{
dp[i][0] = dp[i-1][0]*10 - dp[i-1][1];
dp[i][1] = dp[i-1][0];
dp[i][2] = dp[i-1][1] + dp[i-1][2]*10;
}
}
int main()
{
init();
int T;
scanf("%d",&T);
while(T--)
{
ll n;
scanf("%I64d",&n);
n = n+1;//
int len = 0;
while(n)
{
a[len++] = n%10;
//printf("a...%d ",a[len-1]);
n/=10;
}
// printf("%d
",len);
bool fl = 0;
ll ans = 0;
int last = 0;
for(int i = len-1; i >= 0; i--){
ans+=dp[i][2]*a[i];
if(fl){
ans += dp[i][0]*a[i];
}
else if(a[i]>4) ans+=dp[i][1];
if(last == 4 &&a[i] == 9)fl = 1;
last = a[i];
}
printf("%I64d
",ans);
}
return 0;
}