https://zoj.pintia.cn/problem-sets/91827364500/problems/91827364635
#include <iostream>
#include <map>
#include <string.h>
#include <string>
#include <vector>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <set>
#include <math.h>
#include <stack>
using namespace std;
typedef long long LL;
const int N = 5008;
const int M = 50080;
int n;
int m;
int num[N];
int q_mod[M];
int q_num[M];
bool vis[N];
int father[M];
char tm[10];
string bfs() {
int head = 0;
int tail = -1;
for (int i = 0; i < m; i++) {
if (num[i] != 0) {
q_num[++tail] = num[i];
q_mod[tail] = num[i] % n;
vis[q_num[tail]] = true;
if (q_num[tail] == 0) {
sprintf(tm, "%d", q_num[tail]);
return string(tm);
}
}
}
while (head <= tail) {
int now = q_mod[head];
if (now == 0) {
string ans = "";
int nd = head;
while (nd != -1) {
sprintf(tm, "%d", q_num[nd]);
ans = string(tm) + ans;
nd = father[nd];
}
return ans;
}
for (int i = 0; i < m; i++) {
int nx = (now * 10 + num[i]) % n;
if (vis[nx]) {
continue;
}
vis[nx] = true;
q_num[++tail] = num[i];
q_mod[tail] = nx;
father[tail] = head;
}
head++;
}
return "0";
}
int main() {
std::ios::sync_with_stdio(false);
while (cin >> n >> m) {
for (int i = 0; i < m; i++) {
cin >> num[i];
}
if (n == 0) {
cout << 0 << endl;
continue;
}
sort(num, num + m);
memset(vis, 0, sizeof(vis));
memset(father, -1, sizeof(father));
cout << bfs() << endl;
}
return 0;
}