POJ-1465 Multiple

来源:互联网 发布:钢铁软件 编辑:程序博客网 时间:2024/06/17 04:36

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

223701211

Sample Output

1100

题目大意:

给你一个数n还有m个个位数,让你找到n的最小的倍数,无法找到就输出0.

解题思路:

BFS+余数判重

具体思路在我的另外一篇博客里面有

这题坑点很多。比如卡STL时间,当n为0的时候要输出0等等= =

代码:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 5000 + 10;typedef struct node{    int pre;    int mod;    int digit;}Queue;int n, m;int a[maxn];int vis[maxn];Queue q[maxn];void print(Queue p){    if(p.pre > -1) print(q[p.pre]);    printf("%d", p.digit);}void bfs(){    int front = 0, rear = 0;    for(int i = 0; i < maxn; ++i){        vis[i] = 0;        q[i].pre = -1;        q[i].mod = q[i].digit = 0;    }    for(int i = 0; i < m; ++i){        if(!a[i]) continue;        if(a[i] % n == 0) {            printf("%d\n", a[i]);            return;        }        if(!vis[ a[i] % n ]){            vis[ a[i] % n ] = 1;            q[rear].mod = a[i] % n;            q[rear].digit = a[i];            ++rear;        }    }        while(front < rear){        Queue tmp, p = q[front++];                if(p.mod == 0){            print(p);            puts("");            return;        }                for(int i = 0; i < m; ++i){            tmp.mod = (p.mod * 10 + a[i]) % n;            tmp.digit = a[i];            tmp.pre = front - 1;                        if(!vis[tmp.mod]) {                vis[tmp.mod] = 1;                q[rear++] = tmp;            }        }    }        puts("0");}int main(){    // freopen("test.in", "r+", stdin);    // freopen("test.out", "w+", stdout);        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) puts("0");        else bfs();    }    return 0;}


0 0
原创粉丝点击