1. 程式人生 > >Power Calculus UVA - 1374 叠代加深搜索

Power Calculus UVA - 1374 叠代加深搜索

with 叠代加深搜索 stdin stream style main alc col span

叠代加深搜索經典題目,好久不做叠代加深搜索題目,拿來復習了,我們直接對當前深度進行搜索,註意剪枝,還有數組要適當開大,因為2^maxd可能很大

題目:題目鏈接

AC代碼:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <cstring>
 7 #include <vector>
 8 #include <string
> 9 #include <queue> 10 #include <map> 11 #include <set> 12 13 #define FRER() freopen("in.txt", "r", stdin); 14 #define INF 0x3f3f3f3f 15 16 using namespace std; 17 18 const int maxn = 10000 + 5; 19 20 int num[maxn], vis[maxn], temp[50], maxd, n; 21 22 bool dfs(int, int
); 23 24 int main() 25 { 26 //FRER() 27 ios::sync_with_stdio(0); 28 cin.tie(0); 29 30 temp[0] = 1; 31 for(int i = 1; i < 32; ++ i) 32 temp[i] = temp[i - 1] << 1; 33 while(cin >> n && n) { 34 memset(vis, 0, sizeof(vis)); 35 for
(maxd = 0; ; ++maxd) 36 if(dfs(0, 1)) break; 37 cout << maxd << endl; 38 } 39 return 0; 40 } 41 42 bool dfs(int cur, int s) { 43 if(cur == maxd && s == n) return true; 44 if(cur > maxd) return false; 45 if(s * temp[maxd - cur] < n) return false; 46 num[cur] = s; 47 vis[s] = 1; 48 for(int i = 0; i <= cur; ++i) { 49 int u = num[i] + s; 50 if(!vis[u]) { 51 vis[u] = 1; 52 if(dfs(cur + 1, u)) return true; 53 vis[u] = 0; 54 } 55 u = abs(num[i] - s); 56 if(!vis[u]) { 57 vis[u] = 1; 58 if(dfs(cur + 1, u)) return true; 59 vis[u] = 0; 60 } 61 } 62 vis[s] = 0; 63 return false; 64 }

Power Calculus UVA - 1374 叠代加深搜索