HDU - 3555 Bomb(数位dp)
生活随笔
收集整理的這篇文章主要介紹了
HDU - 3555 Bomb(数位dp)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給定一個整數n,求從1到n的閉區間內含有相鄰“49”的數字的個數。
題目分析:裸的數位dp,這里說一下兩種做法,第一種是正著求,也就是求含有49的數字的個數,第二種是反著求,求不含49的數字的個數,最后再和n做差就好了。
正著求:
規定dp[pos][pre][state]為第pos位上,前一個數為pre,目前狀態為state(所枚舉的這個數字是否含有相鄰的49)時的數字數量。
代碼:
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<stack> #include<queue> #include<map> #include<sstream> #include<cmath> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=800;LL dp[25][10][2];int b[25];LL dfs(int pos,int pre,bool state,bool limit) {if(pos==-1)return state;if(!limit&&dp[pos][pre][state]!=-1)return dp[pos][pre][state];int up=limit?b[pos]:9;LL ans=0;for(int i=0;i<=up;i++){ans+=dfs(pos-1,i,state||i==9&&pre==4,limit&&i==b[pos]);}if(!limit)dp[pos][pre][state]=ans;return ans; }LL solve(LL n) {int cnt=0;while(n){b[cnt++]=n%10;n/=10;}return dfs(cnt-1,-1,false,true); }int main() { // freopen("input.txt","r",stdin);memset(dp,-1,sizeof(dp));int w;cin>>w;while(w--){LL a;cin>>a;cout<<solve(a)<<endl;}return 0; }反著求:
規定dp[pos][state]為第pos位上,目前狀態為state(前一位是否為4)時的數字數量。
代碼:
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<stack> #include<queue> #include<map> #include<sstream> #include<cmath> using namespace std;typedef long long LL;typedef unsigned long long ULL;const int inf=0x3f3f3f3f;const int N=30;LL dp[N][2];int b[N];LL dfs(int pos,int state,bool limit) {if(pos==-1)return 1;if(!limit&&dp[pos][state]!=-1)return dp[pos][state];int up=limit?b[pos]:9;LL ans=0;for(int i=0;i<=up;i++){if(sta&&i==9)continue;ans+=dfs(pos-1,i==4,limit&&i==b[pos]);}if(!limit)dp[pos][state]=ans;return ans; }LL solve(LL n) {int cnt=0;while(n){b[cnt++]=n%10;n/=10;}return dfs(cnt-1,false,true); }int main() { // freopen("input.txt","r",stdin);int w;cin>>w;memset(dp,-1,sizeof(dp));while(w--){LL n;cin>>n;cout<<n-solve(n)+1<<endl;}return 0; }?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的HDU - 3555 Bomb(数位dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数位dp模板+理解
- 下一篇: HDU - 3709 Balanced