Multiple
Time Limit: 1000MS | Memory Limit: 32768K | |
Total Submissions: 7692 | Accepted: 1718 |
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
直接用bfs会超时,还要用同余剪枝,就是余数相同时再加上相同的一个数,余数依旧相同,e是其相同余数 e*10+i还是其相同余数
用vis[ ]记录其是否之前有过相同余数,因为再加的几个数是固定的,相同余数再加后的几个余数依旧固定相等,即可去掉这个分枝
m个数m个数的改变其mark,则可在最后递归输出答案
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
using namespace std;
int vis[5010]; //标记是否出现过此余数,出现过就废掉此支线,同余剪枝
int num[10];
struct point{
int prewei,yu,the;
};
int n,m;
point q[5010];
void print(int ans){// 循环输出结果
if(ans>0){
print(q[ans].prewei);
printf("%d",q[ans].the);
}
}
void bfs(point p){
int i,yu,nr;
int flag=0,mark=1;//flag是不包括当前位的位数,即现在数的位数为flag+1
//mark记录上一个结点是数组中第几个
q[flag]=p;
while(flag<mark){ //22 0 就是=的情况,最多flag=mark-1是数据22 1 3这种
point a=q[flag];
yu=a.yu; //继承老余数
for(i=0;i<m;i++){
nr=(yu*10+num[i])%n; //新余数
if(!vis[nr]&&(a.prewei!=-1||num[i])){//后面的一块让第一位不为0
vis[nr]=1; //以后不再搜索此余数 ,同余剪枝
a.prewei=flag;
a.yu=nr;
a.the=num[i];
q[mark++]=a;
if(nr==0){
print(mark-1);
printf("\n");
return ;
}
}
}
flag++;
}
printf("0\n");
return ;
}
int main(){
int i;
point q[5010];
while(~scanf("%d",&n)){
memset(vis,0,sizeof(vis));
scanf("%d",&m);
for(i=0;i<m;i++){
scanf("%d",&num[i]);
}
sort(num,num+m);
if(n==0){
printf("0\n");
continue;
}
point p;
p.prewei=-1;p.yu=0;p.the=0;
//不包括当前位的位数,当前数的余数,当前加在个位的数
bfs(p);
}
return 0;
}