POJ 1465 Multiple

Multiple
Time Limit: 1000MS Memory Limit: 32768K
Total Submissions: 6410 Accepted: 1386

Description

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).

Input

The input 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.

Output

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:

Sample Input

22
3
7
0
1

2
1
1

Sample Output

110
0


#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
#include <cmath>
#include <algorithm>
#define N 5020
using namespace std;

int n,m;
int a[N];
int f;

struct node
{
    int digit;//数值
    int yu;//余数
    int pre;//用于递归输入结束判断
    int id;//下标
}que[N];

bool b[N];

void output(int id)//可能会出现大数所以递归输出
{
    if(que[id].pre==-1)
    return;
    output(que[id].pre);
    printf("%d",que[id].digit);
}

void bfs()
{
    f=0;
    memset(b,0,n);

    int cnt=1,i,yu;
    int id;

    que[0].pre=-1;
    que[0].yu=0;
    que[0].id=0;
    queue<int> Q;

    Q.push(0);
    while(!Q.empty())
    {
        id=Q.front();
        Q.pop();

        for(i=0;i<m;i++)
        {
            if(que[id].yu==0 &&a[i]==0)continue;
            yu=(que[id].yu*10+a[i])%n;

            if(!b[yu])
            {
                if(yu==0)
                {
                    output(id);
                    printf("%d\n",a[i]);
                    f=1;
                    return;
                }

              b[yu]=1;
              que[cnt].digit=a[i];
              que[cnt].pre=id;
              que[cnt].yu=yu;
              que[cnt].id=cnt;
              Q.push(cnt++);
            }
        }
    }
}

int main()
{
    while(~scanf("%d",&n))
    {
        scanf("%d",&m);

        for(int i=0;i<m;i++)
        scanf("%d",&a[i]);

        sort(a,a+m);
        if(n==0)
        {
            printf("0\n");
            continue;
        }

        bfs();
        if(!f) printf("0\n");

    }
    return 0;
}









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值