zoj 1136 Multiple(数学+bfs)

本文介绍了一种使用广度优先搜索(BFS)算法解决特定数学问题的方法:给定一个整数n和一组数字,寻找由这组数字组成的最小的n的倍数。通过BFS遍历所有可能的数字组合,利用模运算进行优化,最终找到符合条件的最小倍数。

【题目大意】:给你一个数n,以及m个数字,找一个最小的n的倍数,使得这个数仅由m个数字中的任意个组成。


【解题思路】:易知,a%n=x (a*10+b)%n=(x*10+b)%n。然后bfs扫过去就可以了,注意记录余数,和余数的判重。

                            poj要手写queue才能过,不知道为什么


【代码】:

                      

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
                   
using namespace std;
                   
#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define linf 1LL<<60
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

struct Node{
    string num;
    int mod;
    Node(){}
    Node(string a,int b){
        num=a,mod=b;
    }
};
int n,m;
int a[20];
int vis[6000];
string ans;

bool solve_bfs(){
    queue<Node> que;
    que.push(Node("",0));
    memset(vis,0,sizeof(vis));
    while (!que.empty()){
        Node p=que.front();
        que.pop();
        for (int i=0; i<m; i++){
            Node tmp;
            tmp.num=p.num+(char)('0'+a[i]);
            tmp.mod=(p.mod*10+a[i])%n;
            if (tmp.num!="0" && tmp.mod==0) {ans=tmp.num; return true;}
            if (vis[tmp.mod]==0 && tmp.num!="0") {
                que.push(tmp);
                vis[tmp.mod]=1;
            }
        }
    }
    return false;
}


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) cout << 0 << endl;
        else if (solve_bfs()) cout << ans << endl;
        else cout << 0 << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值