Description
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).
Input
The input 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.
Output
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:
Sample Input
22 3 7 0 1 2 1 1
Sample Output
110 0
题意: 给你一个属于[0,4999]的数N和多个十进制单数字.现在要求你输出一个m,这个m是N的最小倍数,且仅有我们之前给出的数字构成.
还有一个需要注意的点是,我们如何表示BFS扩展的每个状态?由于数可能上千位,如果我们每个节点保存int [1000]肯定不行.我们用下面的方式来:
struct Node
{
int digit;//当前状态的个位值
int r;//当前状态值%N的余数
int pre;//当前状态的个位值的连接指针,用来找到所有当前状态的位
}Q[maxn];
这样就可以极大的节省空间.具体代码体会.
注意原题中的digit特指单个数字。
<span style="font-size:18px;">#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=5000+50;
int n,m;
int digit[10];
bool flag[maxn];
struct Node
{
int digit;
int r;
int pre;
}Q[maxn];
int BFS()
{
memset(flag,0,sizeof(flag));
int front=0,tail=1;
Q[front].digit=0;
Q[front].r=0;
Q[front].pre=-1;
while(front<tail)
{
Node node=Q[front];
int r=node.r; //老余数
for(int i=0;i<m;i++)
{
int nr=(r*10+digit[i])%n; //新余数
if(!flag[nr] && (node.pre!=-1 || digit[i]!=0))//错误,忘写了后面这段,我们要保证后继不能生成0
{
flag[nr]=true;
node.r=nr;
node.digit=digit[i];
node.pre=front;
Q[tail++]=node;
if(nr==0) return tail-1;
}
}
front++;
}
return -1;
}
void print(int ans) //递归打印
{
if(ans>0)
{
print(Q[ans].pre);
printf("%d",Q[ans].digit);
}
}
int main()
{
while(scanf("%d",&n)==1)
{
scanf("%d",&m);
for(int i=0;i<m;i++) scanf("%d",&digit[i]);
sort(digit,digit+m); //错误,忘写这句了
if(n==0){printf("0\n"); continue;}
int ans=BFS();
if(ans==-1) printf("0\n");
else {print(ans); puts("");}
}
return 0;
}
</span>