hdu 3652 B-number(數位dp)

來源:互聯網
上載者:User

hdu 3652 B-number(數位dp)

http://acm.hdu.edu.cn/showproblem.php?pid=3652


大致題意:"B-number"即一個整數含有子串"13"且被13整除。求1-n之間這樣的數的個數。


思路:有兩個限制條件:含有子串“13”和能被13整除。那麼設dp[site][mod][flag],表示到第site位對13取餘為mod且標記為flag的數的個數。flag表示是否含有子串"13"。然後進行記憶話搜尋。


#include <stdio.h>#include <iostream>#include <map>#include <stack>#include <vector>#include <math.h>#include <string.h>#include <queue>#include <string>#include <stdlib.h>#include <algorithm>#define LL long long#define _LL __int64#define eps 1e-8#define PI acos(-1.0)using namespace std;int dp[15][15][5];int dig[15];//flag = 0表示前一個不是1,flag = 1表示前一個是1,flag = 2表示出現"13"。int dfs(int site, int mod, int flag, int up){    if(site == 0)        return mod == 0 && flag == 2; //當mod為0且有"13"時,返回1    if(!up && dp[site][mod][flag] != -1)//記憶化        return dp[site][mod][flag];    int len = up ? dig[site] : 9;    int ans = 0;    for(int i = 0; i <= len; i++)    {        int tmod = (mod*10 + i) % 13;        int tflag = flag;        if(flag == 1 && i == 3)            tflag = 2;        else if(flag == 0 && i == 1)            tflag = 1;        else if(flag == 1 && i != 1)            tflag = 0;        ans += dfs(site-1, tmod, tflag, up && (i == len) );    }    if(!up)        dp[site][mod][flag] = ans;    return ans;}int cal(int n){    int cnt = 0;    while(n)    {        dig[++cnt] = n % 10;        n /= 10;    }    memset(dp,-1,sizeof(dp));    return dfs(cnt,0,0,1);}int main(){    int n;    while(~scanf("%d",&n))    {        printf("%d\n",cal(n));    }    return 0;}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.