• Power Calculus UVA


    迭代加深搜索经典题目,好久不做迭代加深搜索题目,拿来复习了,我们直接对当前深度进行搜索,注意剪枝,还有数组要适当开大,因为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 }
  • 相关阅读:
    Jzoj5417 方阵
    Jzoj5414 幸运值
    PAT甲级——A1036 Boys vs Girls
    PAT甲级——A1035 Password
    PAT甲级——A1030 Travel Plan
    PAT甲级——A1026 Table Tennis
    PAT甲级——A1022 Digital Library
    PAT甲级——A1018 Public Bike Management
    PAT甲级——A1021 Deepest Root
    PAT甲级——A1020 Tree Traversals
  • 原文地址:https://www.cnblogs.com/fan-jiaming/p/9788928.html
Copyright © 2020-2023  润新知