首页 > 代码库 > hdoj 1455 Sticks 【dfs】

hdoj 1455 Sticks 【dfs】

题意:找最短的木棍能够组成的长度,

hdoj  1518 的加强版

代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
using std::sort;
#define M 70
int s[M], vis[M];
int n, ans;
int cmp(int a, int b)
{
	return a > b;
}
int dfs(int cou, int cur, int pos)
{
	if(cou == n) return 1;
	int i;
	for(i = pos; i < n; i ++){
		if(vis[i]) continue;
		if(cur+s[i] < ans){
			vis[i] = 1;
			if(dfs(cou+1, cur+s[i], i+1)) return 1;
			vis[i] = 0;
			if(cur == 0) return 0;
			while(s[i] == s[i+1]&&i+1<n) ++i;
		}
		else if(cur+s[i] == ans){
			vis[i] = 1;
			if(dfs(cou+1, 0, 0)) return 1;
			vis[i] = 0;
			return 0;
		}
	}
	return 0;
}
int main()
{
	int i, j;
	while(scanf("%d", &n), n){
		int sum = 0;
		for(i = 0; i < n; i ++){
			scanf("%d", &s[i]);
			sum+=s[i];
		}
		sort(s, s+n, cmp);
		for(i = n; i > 0; i --){
			if(sum%i == 0&&(sum/i) >= s[0]){
				ans = sum/i;
				memset(vis, 0, sizeof(vis));
				if(dfs(0, 0, 0)){
					printf("%d\n", ans);
					break;
				}
			}
		}
	}
	return 0;
} 

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1455

hdoj 1455 Sticks 【dfs】