HDU 3652 數位DP

首先知道一個定理: (a+b)%m = (a%m+b%m)%m;

思路

單獨拿出一位來看,是否能被13整除或者從cnt到該位有沒有出現出13

整除量使用mod記錄,是否出現過13用have記錄,have==1是前一位是1,have==2,已經出現過13.

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>

using namespace std;
int digits[15];
int dp[15][15][3];
int dfs( int pos,int mod,int limit,int have ) {
    if ( pos<0 )
        return mod==0&&have==2;
    else {
        if ( !limit&&dp[pos][mod][have]!=-1 )
            return dp[pos][mod][have];
        int last = limit? digits[pos]:9 ;
        int ans = 0 ;
        for (int i=0; i<=last; i++ ) {
            if ( have==2 ) {
                ans += dfs( pos-1,(mod*10+i)%13,limit&&i==last,2 );
            } else if ( have==1&&i==3 ) {
                ans += dfs( pos-1,(mod*10+i)%13,limit&&i==last,2 );
            } else {
                ans += dfs( pos-1,(mod*10+i)%13,limit&&i==last,i==1?1:0 );
            }
        }
        if ( !limit )
            dp[pos][mod][have] = ans;
        return ans;
    }
}
int judge( int x ) {
    int cnt = 0;
    while ( x ) {
        digits[ cnt++ ] = x%10;
        x /= 10;
    }
    return dfs( cnt-1,0,1,0 ) ;
}
int main()
{
    int n;
    memset( dp,-1,sizeof dp);
    while ( scanf("%d",&n)!=EOF ) {
        cout<<judge(n)<<endl;
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章