Addition Chains POJ - 2248(迭代加深搜索)

題意:傳送門
題解:對於這個題需要找出符合長度最小的長度,對於100100這個數而言,1+2+4+6+10+16+26+42>1001+2+4+6+10+16+26+42>100,所以有答案的情況大概在1010以內就存在了,可以直接使用迭代加深搜索,當到達某個深度搜到了答案時就是最短長度了,當然對於每個搜索內部還可以派出等效冗餘,如果x[i]+x[j]x[i]+x[j]是相等的,搜索多次也是無用,使用boolbool數組進行標記,加以判重,避免重複搜索某一個和。
code:code:

#include<iostream>
#include<cstdio>
using namespace std;
const int N=1e2+50;
int n,path[N];
bool dfs(int u,int depth)
{
    if(u==depth)return path[u-1]==n;
    bool st[N]={false};
    for(int i=u-1;i>=0;i--){
        for(int j=u-1;j>=0;j--){
            int t=path[i]+path[j];
            if(t<=n&&t>path[u-1]&&!st[t]){
                st[t]=true;
                path[u]=t;
                if(dfs(u+1,depth))return true;
            }
        }
    }
    return false;
}
int main()
{
    while(cin>>n&&n){
        path[0]=1;
        int depth=1;
        while(!dfs(1,depth))depth++;
        for(int i=0;i<depth;i++)cout<<path[i]<<" ";
        cout<<endl;
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章