Multiple
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 Source |
这题注意几点:
1.从小往大的搜 得到最优解
2.取余判重
3.特殊情况的处理 如0 或者开始就给出了n的倍数等
4.最后答案的位数可能很大 不能用int或long long 处理
我是这样处理的 每一个节点只存有效值 以及加进来的dight 这样就不用处理大数了
比如 n=7 现在扩展出来的为9 则有效值为2
因为如果A,B对于X的余数相同
那么
(10*A+d[i])%x
(10*B+d[i])%x
的意义是一样的
感想:这题开始还是不敢下手的 后来下手了感觉也不是那么难 敲出来了 不过WA了 因为我天真的用int处理了 ╮(╯▽╰)╭
代码;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define maxn 5005
using namespace std;
int n,m,ans;
int a[15];
bool vis[maxn];
struct Node
{
int d; // 当前节点所加的dight
int val; // 有效值
int pre; // 上一个节点编号
}cur,now,q[maxn];
bool bfs()
{
int i,j,nx,tx;
int head=0,tail=-1;
memset(vis,0,sizeof(vis));
cur.pre=-1;
for(i=1;i<=m;i++)
{
if(a[i]!=0&&!vis[a[i]%n])
{
vis[a[i]%n]=1;
cur.d=a[i];
cur.val=a[i]%n;
q[++tail]=cur;
}
}
while(head<=tail)
{
nx=q[head].val;
if(nx%n==0)
{
ans=head;
return true;
}
for(i=1;i<=m;i++)
{
tx=nx*10+a[i];
if(!vis[tx%n])
{
vis[tx%n]=1;
cur.d=a[i];
cur.pre=head;
cur.val=tx%n;
q[++tail]=cur;
}
}
head++;
}
return false ;
}
void output(int k) // 递归输出答案
{
if(k==-1) return ;
else
{
output(q[k].pre);
printf("%d",q[k].d);
}
}
int main()
{
int i,j,flag;
while(~scanf("%d",&n))
{
flag=0;
scanf("%d",&m);
for(i=1;i<=m;i++)
{
scanf("%d",&a[i]);
}
if(n==0)
{
printf("0\n");
continue ;
}
sort(a+1,a+m+1);
for(i=1;i<=m;i++)
{
if(a[i]%n==0&&a[i]!=0)
{
ans=a[i];
flag=1;
break ;
}
}
if(flag)
{
printf("%d\n",ans);
continue ;
}
if(bfs()) output(ans);
else printf("0");
printf("\n");
}
return 0;
}