杭电hdu 1455 sticks 深度优先搜索

http://acm.hdu.edu.cn/showproblem.php?pid=1455

都说经典的题最练习人的大脑,这个题就是,理解了深度优先算法的精髓,还要去能够灵活的运用才行,本题就是一个考验我智力的一个题。结果还是才考了别人的代码才写出了自己的代码。

//深度优先搜索
#include <iostream>

using namespace std;

#include <algorithm>
#include <cstdio>
#include <cstring>

int sticks[65];
bool used[65], flag;

int n, len, piece;

bool cmp(int a, int b)
{
	return a > b;
}

void dfs(int pos, int cur, int cnt)
{
	if(flag)return ;//已搜索到当前解就返回
	if(cur == len){
		cnt ++;
		if(cnt == piece){//当前解可行
			flag = true;
		}
		dfs(0,0,cnt);
		return ;
	}
	if(pos == n)return ;//搜到了最后一根stick
	int pre = -1;
	for(int i = pos; i < n; i ++){//从pos的位置继续搜索
		if(!used[i] && sticks[i] != pre && cur + sticks[i] <= len){
			pre = sticks[i];
			used[i] = true;
			dfs(i + 1, sticks[i] + cur, cnt);
			used[i] = false;
			if(flag||pos==0)return;
		}
	}
}

int main()
{
//	freopen("input.txt", "r+", stdin);
	int i;
	int sum, max;
	while(scanf("%d", &n)&&n){
		sum = 0;
		for(i = 0; i < n; i ++){
			scanf("%d", &sticks[i]);
			sum += sticks[i];
		}
		sort(sticks, sticks+n, cmp);//降序排序
		max = sticks[0];
		for(i = max; i <= sum; i ++){//i为当前搜索的每根sitck的长度
			if(sum%i==0){
				piece = sum/i;//stick 的数目
				len = i;
				memset(used, false, sizeof(used));
				flag = false;
				dfs(0,0,0);
				if(flag)break;
			}
		}
		printf("%d\n", len);
	}
	return 0;
}

经过测试,在有些系统里面还会超时,经过继续剪枝,终于AC了两千多ms。

#include <iostream>

using namespace std;

#include <cstdio>
#include <cstring>
#include <algorithm>

int cmp(const void *a, const void *b)
{
	return (*(int *)b)-(*(int *)a);
}

bool used[65];
int sticks[65];
int n, len, piece;

bool dfs(int pos, int cur, int cnt)
{
	bool flag = (cur==0 ? true : false);
	if(cnt == piece){
		return true;
	}
	for(int i = pos; i < n; i ++){
		if(used[i])continue;
		if(cur + sticks[i] == len){
			used[i] = true;
			if(dfs(0,0,cnt+1))return true;
			used[i] = false;
			return false;
		}
		else if(cur + sticks[i] < len){
			used[i] = true;
			if(dfs(i+1, cur+sticks[i], cnt))
				return true;
			used[i] = false;
			if(flag)return false;
			while(sticks[i] == sticks[i+1])i++;
		}
	}
	return false;
}

int main()
{
//	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);
	int sum, i;
	while(scanf("%d", &n)&&n){
		sum = 0;
		for(i = 0; i < n; i ++){
			scanf("%d", &sticks[i]);
			sum += sticks[i];
		}
		qsort(sticks, n, sizeof(sticks[0]), cmp);
//		printf("%d\n", sticks[n-1]);
		memset(used, false, sizeof(used));
		for(len = sticks[0]; len <= sum; len ++){
			if(sum%len==0){
				piece = sum/len;
				if(dfs(0,0,0)){
					printf("%d\n", len);
					break;
				}
			}
		}
	}
	return 0;
}
相关文章
相关标签/搜索