POJ 1426 - Find The Multiple - [DP][BFS]

题目连接:http://poj.org/problem?id=1426ios

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.

Inputgit

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数组

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.

Sample Inputspa

2
6
19
0

Sample Outputcode

10
100100100100100100
111111111111111111

 

题意:blog

给出一个在 $[1,200]$ 范围内的整数 $n$,要求找到一个只包含 $0$ 和 $1$ 的十进制整数,是 $n$ 的倍数,能够保证 $m$ 不会超过 $100$ 位。ip

 

题解:ci

首先,不一样于从低位向高位搜索,咱们从高位向低位搜索,get

根据手算除法的原理,高位模 $n$ 的余数,应当乘 $10$ 后加到其低一位上去,input

而因为一位一位的搜索产生的确定是一棵二叉树,不妨参考彻底二叉树按数组形式存储的方式开一个 $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);
        }
    }
}