poj2248Addition Chains(IDA*搜索)

题目链接

题意

f[0] = 1,f[1] = 2
f[k] = f[i] + f[j] (0<=i,j<==k-1)
求当n = f[k] 时,输出前k项 (k最小时)

解题思路

典型的IDA*算法,K从1开始枚举,当k可行时,结束搜索.
很容易发现f[k]是递增的,所以当搜索深度为step时,f[step] = f[1...step-1] + f[step-1],这样就很快地会搜索出解.

AC代码

#include<vector>
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<set>
#include<cstring>
#include<functional>
#include<map>
#include<cmath>
#include<string>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<int,pii> PII;
const int maxn = 1e6+5;
int sta[maxn];

bool idastar(int n,int step,int top)
{
    for(int i=0;i<step;i++){
        int k = sta[i]+ sta[step-1];
        if(k==n){
            for(int i=0;i<step;i++){
                cout << sta[i];
                cout << " ";
            }
            cout << k << endl;
            return true;
        }
        if(step < top){
            sta[step] = k;
            bool ok = idastar(n,step+1,top);
            if(ok)return true;
        }
    }
    return false;
}

int main(int argc, char const *argv[])
{
    int n = 0;
    while(cin >> n,n){
        int top = 0;
        if(n==1){
            cout << "1" << endl;
            continue;
        }else if(n==2){
            cout << "1 2" << endl;
            continue;
        }
        sta[0] = 1;
        sta[1] = 2;
        while(++top){
            if(idastar(n,2,top))break;
        }
    }
    
    return 0;
}
posted @ 2018-10-16 12:35  django_lf  阅读(127)  评论(0编辑  收藏  举报