uva529

思路

昨天打了这道题,一直没想出来深度改变后该怎么搜索,今天才知道迭代加深。 总结来说,迭代加深就是规定输出最小的深度就可以从大到小枚举深度。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

#include<iostream>
#include<cmath>
#include<cstring>

using namespace std ;

int N ; int m ; int flag = 0 ;
int ans[1000] ;

int ( ) {
char ch = 0 ; int res = 0 ; int f = 1 ;
while ( ch >'9' || ch < '0' ) {
if ( ch == '-' ) {
ch = getchar ( ) ;
f = -1 ;
break ;
}
ch = getchar ( ) ;
}
while ( ch >= '0' && ch <= '9' ) res = res * 10 + ch - 48 , ch = getchar ( ) ;
return res * f ;
}

void search ( int step , int f ) {
if ( step == m + 1 ) {
if ( ans[m] == N )
flag = 1 ; return ;
}
for ( int i = step - 1 ; i >= f ; i -- ) {
for ( int j = i ; j >= 1 ; j -- ) {
ans[step] = ans[i] + ans[j] ;
int now = ans[step] ;
for ( int i = m - step ; i >= 1 ; i -- )now *= 2 ;
if ( now < N ) break ;
search ( step + 1 , i + 1 ) ;
if ( flag ) return ;
ans[step] = 0 ;
}
}
}

void print ( ) {
for ( int i = 1 ; i < m ; i ++ ) printf ( "%d " , ans[i] ) ;
printf ( "%dn" , ans[m] ) ;
return ;
}

int main ( ) {
N = read ( ) ;
ans[1] = 1 ;
while ( N ) {
if ( N == 1 ) {
printf( "1n" ) ;
N = read ( ) ;
continue ;
}
flag = 0 ;
for ( int i = 2 ; i <= N ; i ++ ) {
m = i ;
search ( 2 , 1 ) ;
if ( flag ) {
print ( ) ; break ;
}
}
N = read ( ) ;
}
}