POJ-1465 Multiple

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

题目大意:

给你一个数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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值