POJ 1426 - Find The Multiple - [DP][BFS]
阿新 • • 發佈:2018-09-23
more reat namespace find hat array href 原理 write
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.
題目鏈接:http://poj.org/problem?id=1426
Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.Output
Sample Input
2 6 19 0
Sample Output
10 100100100100100100 111111111111111111
題意:
給出一個在 $[1,200]$ 範圍內的整數 $n$,要求找到一個只包含 $0$ 和 $1$ 的十進制整數,是 $n$ 的倍數,可以保證 $m$ 不會超過 $100$ 位。
題解:
首先,不同於從低位向高位搜索,我們從高位向低位搜索,
根據手算除法的原理,高位模 $n$ 的余數,應當乘 $10$ 後加到其低一位上去,
而由於一位一位的搜索產生的肯定是一棵二叉樹,不妨參考完全二叉樹按數組形式存儲的方式開一個 $dp[i]$ 數組,
對於任意一個節點 $i$,從根節點 $1$ 走到當前節點 $i$ 生成的就是一個01十進制整數 $m$,而 $dp[i]$ 存儲的,就是這個 $m$ 模 $n$ 的余數,
所以就有狀態轉移方程:
$\begin{array}{l} dp[2 \times i] = (dp[i] \times 10)\% n \\ dp[2 \times i + 1] = (dp[i] \times 10 + 1)\% n \\ \end{array}$
考慮完全二叉樹的存儲形式,我們完全可以用循環代替BFS。
AC代碼:
#include<iostream> #include<vector> using namespace std; const int maxn=5e6; int n; int dp[maxn]; vector<int> ans; int main() { while(cin>>n && n) { dp[1]=1%n; int now; for(int i=1;;i++) { if(!(dp[i*2]=dp[i]*10%n)) {now=i*2;break;} if(!(dp[i*2+1]=(dp[i]*10+1)%n)) {now=i*2+1;break;} } ans.clear(); while(now) { ans.push_back(now%2); now/=2; } for(int i=ans.size()-1;i>=0;i--) cout<<ans[i]; cout<<endl; } }
當然,不難發現,其實所有的答案不會超過 $1,111,111,111,111,111,110$,也就是 $1e18$ 量級,不超過 long long 類型的 $9,223,372,036,854,775,807$,
所以就算用從低位向高位進行01枚舉的普通BFS也完全可以搞233:
#include<iostream> #include<queue> using namespace std; typedef long long ll; int n; queue<ll> q; int main() { while(cin>>n && n) { while(!q.empty()) q.pop(); q.push(1); while(!q.empty()) { ll x=q.front();q.pop(); ll y=x*10,z=x*10+1; if(y%n==0) {cout<<y<<endl;break;} if(z%n==0) {cout<<z<<endl;break;} q.push(y),q.push(z); } } }
POJ 1426 - Find The Multiple - [DP][BFS]