reference:http://blog.youkuaiyun.com/u013480600/article/details/26458435
Multiple
Time Limit: 1000MS | Memory Limit: 32768K | |
Total Submissions: 7682 | Accepted: 1717 |
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.
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:
An example of input and output:
Sample Input
22 3 7 0 1 2 1 1
Sample Output
110 0
Source
题意:给你m个数,用这些数字组成最小的可以被n整除的数,不行就输出-1.
思路:m个数排序后直接广搜,剪枝为出现过的余数就跳过,用数组保存节点用于输出结果。
# include <iostream>
# include <cstdio>
# include <queue>
# include <cstring>
# include <algorithm>
using namespace std;
int n, m, a[10], vis[5050];
struct node
{
int num;//数字
int pre;//上一个节点
int cal;//取模结果
}q[5050];
int bfs()
{
int l=0, r=1;
node tmp;
tmp.cal = 0;
tmp.pre = -1;
tmp.num = 0;
q[l] = tmp;
while(l<r)
{
node t = q[l];
for(int i=0; i<n; ++i)
{
int nnum = ((t.cal)*10+a[i]) % m;
if(!vis[nnum] && (t.pre != -1 || a[i]!= 0))//没有前导0
{
vis[nnum] = 1;
node ne;
ne.cal = nnum;
ne.num = a[i];
ne.pre = l;
q[r++] = ne;
if(nnum == 0)
return r-1;
}
}
++l;
}
return -1;
}
void print(int x)
{
if(q[x].pre != -1)
{
print(q[x].pre);
printf("%d",q[x].num);
}
}
int main()
{
while(~scanf("%d%d",&m,&n))
{
if(m==0)
{
puts("0");
continue;
}
memset(q, 0, sizeof(q));
memset(vis, 0, sizeof(vis));
for(int i=0; i<n; ++i)
scanf("%d",&a[i]);
sort(a, a+n);
int ans = bfs();
if(ans == -1)
printf("0");
else
print(ans);
puts("");
}
return 0;
}