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;
然后开个数组,判重 余数相同就是代表不可行
#include <iostream> #include <stdio.h> #include <queue> #include <stack> #include <set> #include <vector> #include <string.h> #include <algorithm> using namespace std; struct node { int digit; int pre; int yu; int id; }rc[5555]; int d[102]; bool b[5000]; int n,m; void output(int id) { if(rc[id].pre==-1) return; output(rc[id].pre); printf("%d",rc[id].digit); } int f; void BFS() { f=0; memset(b,0,n); int cnt=1,i,yu; int id; rc[0].pre=-1; rc[0].yu=0; rc[0].id=0; queue<int> Q; Q.push(0); while(!Q.empty()) { id=Q.front();Q.pop(); for(i=0;i<m;i++) { if(rc[id].yu==0&&d[i]==0) continue; yu=(rc[id].yu*10+d[i])%n; if(!b[yu]) { if(yu==0) { output(id); printf("%d\n",d[i]); f=1; return; } b[yu]=1; rc[cnt].digit=d[i]; rc[cnt].pre=id; rc[cnt].yu=yu; rc[cnt].id=cnt; Q.push(cnt++); } } } } int main() { int i; while(scanf("%d",&n)!=EOF) { scanf("%d",&m); for(i=0;i<m;i++) scanf("%d",&d[i]); sort(d,d+m); if(n==0) {printf("0\n");continue;} BFS(); if(!f) printf("0\n"); } return 0; }