HOJ 1018 Multiple

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

The input file has several data sets separated by an empty line, each data set having the following format:

On the first line - the number N
On the second line - the number M
On the following M lines - the digits X1,X2..XM.

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

An example of input and output:


Input

22
3
7
0
1

2
1
1

Output

110
0

题目意思是,找到一个N的最小倍数,使得这个数只由给定的数字组成,如110是22的倍数,只由1和0组成。

可以先看个特殊的例子,见此博客: http://blog.csdn.net/lyy289065406/article/details/6647917

现在我们把它扩展到不止是0 1组成的数。代码如下:

#include <iostream>
#include <algorithm>
#define MAX 200000
using namespace std;


int mod[MAX];


void print(int i,int m,int arr[])
{
    if(i<=0)
    {
        return;
    }
    print((i-1)/m,m,arr);
    cout<<arr[(i-1)%m];
}
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        if(n==0)
        {
            cout<<0<<endl;
            continue;
        }
        int arr[m];
        int i=0;
        bool flag=true;
        for(i=0;i<m;i++)
        {
            cin>>arr[i];
        }
        sort(arr,arr+m);
        for(i=0;i<m;i++)
        {
            if(arr[i]%n==0&&arr[i]!=0) //给定的M个数字里,可能会有N的倍数,那么直接就是这个了
            {
                flag=false;
                cout<<arr[i]<<endl;
                break;
            }
        }
        if(!flag)
        {
            continue;
        }
        for(i=0;i<m;i++)
        {
            mod[i]=arr[i];
        }
        for(i=m;i<MAX;i++)
        {
            mod[i]=(mod[i/m-1]*10+arr[i%m])%n;
            if(mod[i/m-1]==0)
            {
                mod[i]=0;
                continue;
            }
            if(mod[i]==0)
            {
                flag=false;
                break;
            }
        }
        if(flag)
        {
            cout<<0<<endl;
        }
        else
        {
            print(i+1,m,arr);
            cout<<endl;
        }
    }
    return 0;
}


我们用上面题目的第一个例子来说明:N=22,M=3,数字为7,0,1.首先N!=0,然后三个数字里没有一个是N的倍数,然后我们把7,0,1排序并存到mod数组里,即mod[0]=0,mod[1]=1,mod[2]=7,然后广度优先遍历,mod[3]=0,mod[4]=0,mod[5]=0,表示00,01,07都记为0,因为一个数不会以0开头,然后mod[6]=10,mod[7]=11,mod[8]=17,

然后m[9]=70%22=4,m[10]=71%22=5,m[11]=77%22=11,....就这么一直下去,直到m[25]=110%22=0,结束。我们其实是把一棵搜索树的广度优先遍历放到数组里来实现了,非常简洁。我们可以画个搜索树,然后知道了i值,然后我们就可以知道其父节点以及祖先节点的值。

        

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值