TOJ3031: Multiple bfs

3031: Multiple 

Time Limit(Common/Java):2000MS/6000MS     Memory Limit:65536KByte
Total Submit: 60            Accepted:10

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

Sample Output

Source

Southeastern Europe 2000

这个题目可能没那么爽啊,就是给你m个数字,然后用这些数字就构造n的倍数

首先肯定贪心取啊,然后就是大数取余,所以这个时候同余的,然后bfs就完了

 

#include<stdio.h>
#include<string.h>
#include<algorithm>
const int N=5005;
struct T
{
    int res,pre,digit;
} q[N],t;
int n,m,a[20];
bool vis[N];
void print (int x)
{
    if(q[x].pre==-1)return;
    print(q[x].pre),printf("%d",q[x].digit);
}
int bfs()
{
    q[0]= {0,-1,0},memset(vis,0,sizeof vis);
    int tot=0,lst=1;
    while(tot<lst)
    {
        t=q[tot];
        for(int i=0,t1; i<m; i++)
        {
            t1=(t.res*10+a[i])%n;
            if(!a[i]&&t.pre==-1)continue;
            if(!vis[t1])vis[t1]=1,q[lst++]= {t1,tot,a[i]};
            if(!t1)
            {
                print(lst-1),printf("\n");
                return 1;
            }
        }
        tot++;
    }
    return 0;
}

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

 

 

 

posted @ 2018-08-09 16:38  暴力都不会的蒟蒻  阅读(219)  评论(0编辑  收藏  举报