zoj 1136 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

题意:求N的最小的正整数倍数是否能由给出的M个整数(0-9)给出。

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool visit[5010];   //余数判重
int x[10];
int n;
struct node
{
    string num;
    int key;  //余数
};
queue<node>q;
int m;
int bfs()
{
    node h,t;
    h.num="";
    h.key=0;
    q.push(h);
    int k;
    while (!q.empty())
    {
        t=q.front();
        q.pop();
        for (int i=0; i<m; i++)
        {
            k=t.key*10+x[i];
            if(!k)
            {
                continue;
            }
            k=k%n;
            if(k==0)    //找到了
            {
                cout<<t.num<<(char)(x[i]+'0')<<endl;
                return 0;
            }
           if(!visit[k])   //如果没有出现过这个余数则继续
           {
               h.num=t.num+(char)(x[i]+'0');
               h.key=k;
               visit[k]=true;
               q.push(h);
           }
        }
    }
    return 1;    //没找到
}
int main()
{
    while (cin>>n)
    {
        cin>>m;
        for (int i=0; i<m; i++)
        {
            cin>>x[i];
        }
        sort(x, x+m);
        memset(visit, false, sizeof(visit));
        while (!q.empty())
        {
            q.pop();
        }
        if(!n||bfs())
        {
            cout<<"0"<<endl;
        }
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值