ZOJ 1136 Multiple (BFS)

时间:2023-03-09 19:51:08
ZOJ 1136 Multiple (BFS)

Multiple


Time Limit: 10 Seconds      Memory Limit: 32768 KB

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).

The input file 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.

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:

Input

22
3
7
0
1

2
1
1

Output

110
0

题意:给m个数随意拼成一个最小n的倍数。

思路:bfs 输出的时候相当于遍历路径一边,所以有pre.

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
using namespace std; const int INF=0x3f3f3f3f;
const double eps=1e-;
const double PI=acos(-1.0);
#define maxn 5000 struct Node
{
int num, pre, id, yu;
};
Node node[maxn];
int vis[maxn];
int n, m;
int a[maxn];
void output(int id)
{
if(node[id].pre == -)
return;
output(node[id].pre);
printf("%d", node[id].num);
}
void bfs()
{
memset(vis, , sizeof vis);
node[].id = ;
node[].pre = -;
node[].yu = ;
int cnt = ;
queue<int> q;
q.push();
while(!q.empty())
{
int id = q.front();
q.pop();
for(int i = ; i < m; i++)
{
if(node[id].yu == && a[i] == )
continue;
int yu = (node[id].yu*+ a[i])%n;
if(!vis[yu])
{
if(yu == )
{
output(id);
printf("%d\n", a[i]);
return;
}
vis[yu] = ;
node[cnt].pre = id;
node[cnt].num = a[i];
node[cnt].yu = yu;
node[cnt].id = cnt;
q.push(cnt++);
}
}
}
printf("%d\n", );
}
int main()
{
while(~scanf("%d",&n))
{
scanf("%d", &m);
for(int i = ; i < m; i++) scanf("%d", &a[i]);
sort(a, a + m);
if(n == )
printf("%d\n", );
else
bfs();
}
return ;
}