【DFS】2022牛客寒假集訓5 D-數位小孩
阿新 • • 發佈:2022-02-13
D - 數位小孩
題目來源:2022牛客寒假演算法基礎集訓營5
題目連結:D-數位小孩_2022牛客寒假演算法基礎集訓營5 (nowcoder.com)
題目
九峰最近沉迷數位dp,這天他又造了個數位dp題:
給出一個區間[l,r][l,r][l,r],求這個區間內有多少個數字滿足如下條件:
1.每相鄰兩個數位和為素數
2.其中至少一個數位為1
3.沒有前導0
請你編寫程式幫他該題
思想
本題可以用數位dp做(但我是蒟蒻,我不會數位dp),因為此題資料量較小,只有不到25個數位,所以可以用DFS來暴力求解。
利用的是素數環的思想。
注意
1、題目要求至少有一個數位為1,於是用到了一個 f標記 和 或的性質
程式碼
#include <algorithm> #include <cstring> #include <iostream> #include <queue> #include <vector> #define SF ios::sync_with_stdio(false), cin.tie(0), cout.tie(0) using namespace std; typedef long long ll; typedef pair<ll, ll> P; const int inf = 0x3f3f3f3f; int pr[30]; vector<ll> ans; ll l, r, cnt; void dfs(ll x, ll f) { if (x > r) return; if (f) ans.push_back(x); ll past = x % 10; for (int i = 0; i <= 9; ++i) { if (pr[past + i]) { dfs(x * 10 + i, f | (i == 1)); } } } int main() { SF; cin >> l >> r; pr[2] = pr[3] = pr[5] = pr[7] = pr[11] = pr[13] = pr[17] = pr[19] = 1; for (int i = 1; i <= 9; ++i) { dfs(i, i == 1); } ll num = 0; for (auto x : ans) { if (x >= l) num++; } cout << num << endl; return 0; }