广搜,每个节点有两个值,一个是当前的数字,另一个是余数,用余数可以减少以后的计算量,并且可进行剪枝,从而减少了常数时间的复杂度
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct Node {
string num;
int mod;
Node() {}
Node(string a, int b) {
num = a;
mod = b;
}
};
int n, m;
int a[11];
int vis[50005];
string ans;
bool solve() {
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;
}
else if(vis[tmp.mod] == 0 && tmp.num != "0") {
que.push(tmp);
vis[tmp.mod] = 1;
}
}
}
return false;
}
int main() {
while(scanf("%d%d", &n, &m) != EOF) {
for(int i = 0; i < m; i++) {
scanf("%d", &a[i]);
}
sort(a, a+m);
if(0 == n) cout<< 0<< endl;
else if(solve()) cout<< ans<< endl;
else cout<< 0<< endl;
}
return 0;
}