HDU 3652 3555 數位dp

來源:互聯網
上載者:User
/*    求[1,n]內有多少個數字,該數字有13,且能被13整除   n<=10^9        x % 13 = 0    (pre*10^pos + next) % 13 = 0   pre是之前確定的部分    需要的參數為pre , pos , 狀態have    have記錄pre擁有"13",pos+1位為"1",沒有"13"   分別用have = 2,1,0表示        然後記憶化搜尋*/#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int dp[10][13][3];int digit[10];int dfs(int pos, int pre, int have, bool doing) {if(pos == -1) return have == 2 && pre == 0;if(!doing && dp[pos][pre][have] != -1) return dp[pos][pre][have];int ans = 0;int end = doing ? digit[pos] : 9;for(int i = 0; i <= end; i++) {int npre = (pre*10 + i) % 13;int nhave = have;if(have == 0 && i == 1)nhave = 1;else if(have == 1 && i!= 1)nhave = 0;if(have == 1 && i == 3)nhave = 2;ans += dfs(pos-1, npre, nhave, doing && i == end);}if(!doing)dp[pos][pre][have] = ans;return ans;}int cal(int x) {int pos = 0;while(x) {digit[pos++] = x % 10;x /= 10;}return dfs(pos-1, 0, 0, 1);}int main() {int n;while(~scanf("%d", &n)) {memset(dp, -1, sizeof(dp));printf("%d\n", cal(n));}return 0;}

 

 

3555 是3652的簡單版本。

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace std;long long dp[20][3];int digit[20];long long dfs(int pos, int have, bool doing) {if(pos == -1) return have == 2;if(!doing && dp[pos][have] != -1) return dp[pos][have];long long ans = 0;int end = doing ? digit[pos] : 9;for(int i = 0; i <= end; i++) {int nhave = have;if(have == 0 && i == 4)nhave = 1;else if(have == 1 && i!= 4)nhave = 0;if(have == 1 && i == 9)nhave = 2;ans += dfs(pos-1, nhave, doing && i == end);}if(!doing)dp[pos][have] = ans;return ans;}long long cal(long long x) {int pos = 0;while(x) {digit[pos++] = x % 10;x /= 10;}return dfs(pos-1, 0, 1);}int main() {int t;scanf("%d", &t);while(t--) {long long n;cin >> n;memset(dp, -1, sizeof(dp));cout << cal(n) << 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.