POJ2248——Addition Chains【DFS,迭代加深搜索】

题目连接:http://poj.org/problem?id=2248

题目大意:现在有一个数组其中a[1] = 1,a[m] = n,并且a[1] < a[2] < ........< a[m],现在给你一个数n问,满足条件的m的最小值为多少。其中1 <= n <= 9

大致思路:如果我们按照DFS直接搜索的话,一共有n!个节点十分耗时,这个时候我们可以采用迭代加深搜索,每一次搜索限定好搜索深度,并逐层增加搜索深度,知道找到答案为止。

代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

const int MAXN = 110;
bool vis[MAXN];
int ans[MAXN];
int maxd,n;

bool DFS(int d){
	if(d > maxd){
        if(ans[maxd] == n) return true;
        else return false;
	}
	memset(vis,0,sizeof(vis));
	for(int i = d - 1; i >= 1; i--){
        for(int j = d - 1; j >= 1; j--){
            if(ans[i] + ans[j] <= ans[d - 1]) break;
            if(!vis[ans[i] + ans[j]] && ans[i] + ans[j] <= n){
            	ans[d] = ans[i] + ans[j];
            	vis[ans[d]] = 1;
            	if(DFS(d + 1)) return true;
            }
        }
	}
	return false;
}

int main(int argc, char const *argv[])
{
	while(~scanf("%d",&n) && n){
		bool ok = false;
		ans[1] = 1;
		//ans[0] = 0;
		if(n == 1) { cout << "1" << endl; continue; }
		for(maxd = 2; ; maxd++){
			memset(vis,0,sizeof(vis));
			if(DFS(2)) { ok = true; break; }
		}
		//cout << maxd << endl;
		if(ok){
			for(int i = 1; i < maxd; i++) cout << ans[i] << " ";
            cout << ans[maxd] << endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiang_hehe/article/details/84668522