TOJ 3031 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

Southeastern Europe 2000

 

组队训练赛的一题,智商捉鸡。压根没头绪。看了别人的思路说是用广搜分别枚举每一位然后除以n是否模得0。

还有过程中可以对余数重复剪掉。

代码重新写了一遍。

 

 1 #include <stdio.h>
 2 #include <queue>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 int n,m;
 7 int M[101];
 8 bool visited[6000];
 9 
10 struct Node{
11     int digit;
12     int pre;
13     int mod;
14     int cnt;    
15 }nod[6000];
16 
17 int bfs(){
18     queue<int> Q;
19     memset(visited,0,sizeof(visited));
20     int cur=0;
21     nod[cur].digit=0;
22     nod[cur].pre=-1;
23     nod[cur].mod=0;
24     nod[cur].cnt=cur;
25     Q.push(cur++);
26     while( !Q.empty() ){
27         int now=Q.front();
28         int now_mod;
29         Q.pop();
30         for(int i=0; i<m; i++){
31             if(nod[now].mod==0 && M[i]==0)continue;
32             now_mod=(nod[now].mod*10+M[i])%n;
33             if( !visited[now_mod] ){
34                 visited[now_mod]=1;
35                 if(now_mod==0){
36                     int r[6000];
37                     int index=0;
38                     r[index++]=M[i];
39                     while( nod[now].pre!=-1 ){
40                         r[index++]=nod[now].digit;
41                         now=nod[now].pre;
42                     }
43                     for(int i=index-1; i>=0; i--){
44                         printf("%d",r[i]);
45                     }
46                     printf("\n");
47                     return 1;
48                 }else{
49                     nod[cur].digit=M[i];
50                     nod[cur].pre=nod[now].cnt;
51                     nod[cur].mod=now_mod;
52                     nod[cur].cnt=cur;
53                     Q.push(cur++);
54                 }
55             }
56         }
57     }
58     return 0;    
59 }
60 
61 int main(int argc, char *argv[])
62 {
63     while( scanf("%d",&n)!=EOF ){
64         scanf("%d",&m);
65         for(int i=0; i<m; i++){
66             scanf("%d",&M[i]);
67         }
68         sort(M,M+m);
69         if( n==0 || !bfs() ){
70             puts("0");
71         }
72     }
73     return 0;
74 }

 

你可能感兴趣的:(IP)