hdu3555 數位dp,hdu3555dp

來源:互聯網
上載者:User

hdu3555 數位dp,hdu3555dp

題意:你求出[1,n]中包含49的數的個數;

數位dp

1.dp[i][0] 代表數字長度為len不含49的個數 

2.dp[i][1] 代表數字長度為len不含49但是以9開頭的個數

3.dp[i][2] 代表數字長度為len含有49的個數

代碼:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#define N 500010
#define INF 10000000
#define LL long long
#define eps 10E-9
#define mem(a)  memset(a,0,sizeof(a))
#define w(a)   while(a)
#define s(a)   scanf("%d",&a)
#define ss(a,b)   scanf("%d%d",&a,&b)
#define sss(a,b,c)   scanf("%lld%lld%lld",&a,&b,&c)
#define MAXN 9999
#define MAXSIZE 10
#define DLEN 4
#define MAXN 9999
#define MAXSIZE 10
#define DLEN 4
using namespace std;
LL dp[22][3] = {0};
LL digit[22];
void init(){
    dp[0][0] = 1;
    for(int i=1; i<21; i++){
        dp[i][0] = dp[i-1][0]*10 - dp[i-1][1];//在dp[i-1][0]前面添上0~9,但是要減去dp[i-1][1]    因為4和9構成49
        dp[i][1] = dp[i-1][0];//直接在dp[i-1][0]前面添上9就行了
        dp[i][2] = dp[i-1][2]*10 + dp[i-1][1];//在dp[i-1][2]前面添上0~9,或者在dp[i-1][1]前面添上4
    }
}
LL solve(LL x){
     mem(digit);
     LL len = 0;
     while(x){
        digit[++len] = x%10;
        x/=10;
     }
     digit[len+1]=0;
     LL ans=0;
     bool flag = false;
     for(int i=len; i; i--){
          ans += dp[i-1][2]*digit[i];
          if(flag)
            ans+=dp[i-1][0]*digit[i];
          if(!flag && digit[i]>4)
            ans+=dp[i-1][1];
          if(digit[i+1] == 4 && digit[i] == 9)
            flag = true;
     }
     return  ans;
}
int main(){
    int  t;
    LL n;
    init();
    w(~s(t)){
        w(t--){
           cin>>n;
           cout<<solve(n+1)<<endl;
        }
    }
    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.