zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    python中filter(),map()和reduce()的用法及区别
    Python中的单例模式的几种实现方式的及优化
    python标准库和第三方库的区别
    django和flask的区别
    wtforms
    protobuf学习
    人物FSM
    策略模式
    虚函数调用机制
    虚析构函数
  • 原文地址:https://www.cnblogs.com/django-lf/p/9797290.html
Copyright © 2011-2022 走看看