poj 3134 分类: poj 2015-08-08 23:42 4人阅读 评论(0) 收藏


喜闻乐见的迭代加深搜索

快速幂最多只需要 2logX 次就能得到想要的任何数

然而这道题的答案会更小,迭代加深搜索显然是可以承受的。


剪枝优化:
如果剩余的操作次数都用来将最大数与最大数相乘,
得到的结果仍然比希望得到的数小,那么这个状态就一定是不可行的


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>

template<class Num>void read(Num &x)
{
    char c; int flag = 1;
    while((c = getchar()) < '0' || c > '9')
        if(c == '-') flag *= -1;
    x = c - '0';
    while((c = getchar()) >= '0' && c <= '9')
        x = (x<<3) + (x<<1) + (c-'0');
    x *= flag;
    return;
}
template<class Num>void write(Num x)
{
    if(x < 0) putchar('-'), x = -x;
    static char s[20];int sl = 0;
    while(x) s[sl++] = x%10 + '0',x /= 10;
    if(!sl) {putchar('0');return;}
    while(sl) putchar(s[--sl]);
}

const int size = 2000;

int target, depth;
int mass[size];

bool dfs(int pos)
{
    if(pos > depth || ((mass[pos] << (depth - pos))) < target) return false;

    if(mass[pos] == target) return true;

    for(int i = 1; i <= pos; i++)
    {
        if(mass[pos] + mass[i] <= size)
        {
            mass[pos + 1] = mass[pos] + mass[i];
            if(dfs(pos + 1)) return true;
        }

        if(mass[pos] - mass[i] > 0)
        {
            mass[pos + 1] = mass[pos] - mass[i];
            if(dfs(pos + 1)) return true;
        }
    }
    return false;
}

void solve()
{
    depth = 1, mass[1] = 1;

    while(true)
    {
        if(dfs(1))
        {
            depth--;
            return;
        }

        depth++;
    }

}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("3134.in","r",stdin);
    freopen("3134.out","w",stdout);
#endif

    while(true)
    {
        read(target);

        if(!target) break;

        solve();

        write(depth), puts("");
    }


#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-08 23:42  <Dash>  阅读(160)  评论(0编辑  收藏  举报