POJ1465 Multiple BFS+同余

给你一个数n 然后给你m个数,让你求一个最小的数,这个数是n的倍数,并且由题目中提供的m个数组成。用BFS。

此题可以用同余判断的方法来剪枝。

假如 A%X  ==  B%X  (设A<B)

那么 (A*10+Ki)%X==(B*10+Ki)%X

所以A,B之中我们只要取前面的A就行,因为题目要取最小的数,通过同余我们可以知道,A和B这两个数在末尾添加任何相同的数MOD X之后的余数都是一样的,因此对于比A大的数我们就没有必要去扩展了。B可以直接减掉。即对余数进行标记,已经出现过的余数(即当前得到的数与我之前已经得到的某个数同余),将不再扩展节点。

先对m个数字从小到大排序,这样保证我们前面平凑得到的数字是最小的。越早搜索到的符合题目要求的就是我们要的最小的数。

 

Multiple
Time Limit: 1000MS Memory Limit: 32768K
Total Submissions: 5394 Accepted: 1174

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<stdio.h>
#include<string.h>
#include<algorithm>

using namespace std;

struct node
{
    int mod,dig,pt;
}queue[500];
int flag[5010],a[100];
int front,rear;
int m,n;

void output(int p)
{
    if(queue[p].pt==-1) return;
    output(queue[p].pt);
    printf("%d",queue[p].dig);
}

void bfs()
{
    memset(flag,0,sizeof(flag));
    front=rear=0;
    queue[rear].mod=0;
    queue[rear].dig=0;
    queue[rear].pt=-1;
    rear++;
    while(front<rear)
    {
        node tmp;
        tmp=queue[front];
        for(int i=0;i<n;i++)
        {
            if(!flag[(tmp.mod*10+a[i])%m] && (tmp.pt!=-1 || a[i]>0))
            {
                queue[rear].mod=(tmp.mod*10+a[i])%m;
                queue[rear].dig=a[i];
                queue[rear].pt=front;
                flag[queue[rear].mod]=1;
                if(queue[rear].mod==0)
                {
                    output(rear);
                    printf("\n");
                    return ;
                }
                rear++;
            }
        }
        front++;
    }
    printf("0\n");
}

int main()
{
    while(~scanf("%d",&m))
    {
       scanf("%d",&n);
       for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
       sort(a,a+n);
       if(m==0)
            printf("0\n");
       else
            bfs();
    }

}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值