zoj 1136 Multiple(數學+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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章