求给定M个数组合构成N的最小倍数

给定整数N和M个0到9的数字,寻找N的一个最小正倍数,仅由这些数字组成。通过同余定理和BFS解决,如果存在这样的倍数则输出,否则输出0。代码已通过测试验证。
摘要由CSDN通过智能技术生成

Multiple

Description

a program that,given a natural number N between 0 and 4999 (inclusively), and M distinctdecimal digits X1,X2..XM (at least one), finds the smallest strictly positivemultiple of N that has no other digits besides X1,X2..XM (if such a multipleexists).

Input

The input hasseveral data sets separated by an empty line, each data set having thefollowing format:

On the first line- the number N

On the second line- the number M

On the following Mlines - the digits X1,X2..XM.

Output

For each data set,the program should write to standard output on a single line the multiple, ifsuch a multiple exists, and 0 otherwise.

An example ofinput and output:

Sample Input

22

3

7

0

1

2

1

1

Sample Output

110

0

题目意思:给出一个整数N,和M个0~9的数,求N的一个最小倍数,且该数仅由这M个数构成,不存在则输出0。

 

解题思路:

如果存在最终的数,一定可以写成A1*10^(k-1)+A2*10^(k-2)+...+Ak,Ai属于给出的M个数的集合。k有可能很大,64位整数也可能存不下。注意到最后的结果是N的倍数,假设结果是X,则有X%N=0,注意到结果的多项式形式,显然能想到使用同余定理。我们需要从1位扩展到k位(当然要一步步来),可以用BFS,用余数来记录状态(只需要第一个),这样状态不超过N个,一旦余数为0,我们需要的结果就出来了。

对本题的第一个测试数据而言,其执行过程主要如下:(node的变化过程)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值