题目链接:http://acm.zju.edu.cn/show_problem.php?pid=1530
每次看到special judge总有点怕怕的。不过这个dfs的题目还是不难的。
题目的意思是这样的,给出一个数n,要输出一个数,这个数能乘除n,并且这个数只有0和1,这个数最长是100位。
想法就是直接dfs,每次的选择只有0和1,从高位开始搜。
代码in C++
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1
#include
<
iostream
>
2 using namespace std;
3
4 int notfound ;
5 void search( int a[] , int len , int rem , int n)
6 {
7 if (rem == 0 && notfound)
8 {
9 notfound = 0 ;
10 for ( int i = 0 ; i < len ; i ++ )
11 cout << a[i] ;
12 cout << endl ;
13 return ;
14 }
15 else if (notfound && len < 100 )
16 {
17
18 a[len] = 0 ;
19 search(a,len + 1 , ( 10 * rem) % n , n) ;
20 a[len] = 1 ;
21 search(a,len + 1 , ( 10 * rem + 1 ) % n , n) ;
22 }
23 }
24
25 int main()
26 {
27 int n;
28 int a[ 100 ] ;
29 while (cin >> n && n != 0 )
30 {
31 a[ 0 ] = 1 ;
32 notfound = 1 ;
33 search(a, 1 , 1 , n) ;
34 }
35
36 return 0 ;
37 }
2 using namespace std;
3
4 int notfound ;
5 void search( int a[] , int len , int rem , int n)
6 {
7 if (rem == 0 && notfound)
8 {
9 notfound = 0 ;
10 for ( int i = 0 ; i < len ; i ++ )
11 cout << a[i] ;
12 cout << endl ;
13 return ;
14 }
15 else if (notfound && len < 100 )
16 {
17
18 a[len] = 0 ;
19 search(a,len + 1 , ( 10 * rem) % n , n) ;
20 a[len] = 1 ;
21 search(a,len + 1 , ( 10 * rem + 1 ) % n , n) ;
22 }
23 }
24
25 int main()
26 {
27 int n;
28 int a[ 100 ] ;
29 while (cin >> n && n != 0 )
30 {
31 a[ 0 ] = 1 ;
32 notfound = 1 ;
33 search(a, 1 , 1 , n) ;
34 }
35
36 return 0 ;
37 }