码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-09-23 22:37:00      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:each   pop   The   十进制   hat   NPU   ref   vector   形式   

题目链接: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

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 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]

标签:each   pop   The   十进制   hat   NPU   ref   vector   形式   

原文地址:https://www.cnblogs.com/dilthey/p/9693468.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!