[kuangbin]POJ 1426 Find The Multiple

原题链接
中文题面
因为想练下英语就用英文题面了(bushi)

题目描述

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.

输入

2
6
19
0

输出

10
100100100100100100
111111111111111111

纯暴力考虑

首先这题,我最开始的想法是直接dfs枚举下每个位,但此方法显然行不通。首先因为爆搜的时间复杂度达到了2^100,而且用long long 都存不下,要用高精度解决,就给解题增加了麻烦。

bfs搜索剪枝+同余

搜索顺序(事实上经过题后对数据测试,不剪枝也能过)
我们先得想好搜索顺序再剪枝,对一串数字我们一般从开头或结尾搜,本题因为数字尾部有(0,1)两种可能性,而开头必为1,我们选择从头开始搜,得到一颗搜索树
在这里插入图片描述

同余定理解决高精度问题
设答案为k,则最终的结果一定为k%n==0,我们注意到答案只与余数有关(下文有严格的证明),这样我们就可以把问题转化为对搜索树上的每个数取余,记录余数,就可以避免高精度的产生。
接下来我们来说明该算法的正确性:
先叙述几个同余定理的式子:

1: x * y % n==x % n * y % n
2: (x + y)% n==x % n + y % n

对于任意k都只有如下图两种扩展方式
在这里插入图片描述

准备完了之后我们正式开始叙述为什么可以用余数来代替搜索树上的树:
1 当k%n==0时即可停止搜索,此时余数为0
2 确保一个数经过取余操作后,再次对该数进行扩展时保证其余数不变(这样说明太绕了,我们结合一张图来说明)
在这里插入图片描述

这样高精度的问题也被规避了
剪枝操作
在这里插入图片描述
关于数论同余定理想了解下的可以看看这篇文章:

代码如下

#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;

const int N=210;
typedef pair<string,int> psi;

int n;
bool st[N];

int main(void)
{
    while(cin>>n,n)
    {
        queue<psi> q;
        q.push({"1",1});
        memset(st,0,sizeof st);         //多组数据,重置判重数组

        while(q.size())
        {
            psi t=q.front();
            q.pop();
            int x=t.second;

            if(!x)
            {
                cout<<t.first<<endl;    //当余数为0时找到答案,输出
                break;
            }

            int a=(x*10)%n;             //扩展0
            if(!st[a])
            {
                st[a]=true;
                q.push({t.first+"0",a});
            }

            int b=(x*10+1)%n;           //扩展1
            if(!st[b])
            {
                st[b]=true;
                q.push({t.first+"1",b});
            }
        }
    }

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值