(HDU1455)Sticks-DFS

                                            Sticks

             Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
                           Total Submission(s): 13135    Accepted Submission(s): 4031


 

Problem Description

George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.

 

 

Input

The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.

 

 

Output

The output file contains the smallest possible length of original sticks, one per line.

 

 

Sample Input

9 5 2 1 5 2 1 5 2 1

4 1 2 3 4

0

 

Sample Output

6 5

题目分析:

许多木棍长度相等的木棍被切割成许多小木棍,问这些木棍长度的最小长度。

当时想了半天,就是不知道怎么DFS,感觉搜完之后不知道怎么确保木棍全部被选上。后来看了别人的题解犹如提壶灌顶(醍醐灌顶),现在感觉头还有点疼。发现自己的想法太线性了,我想的是从头到尾搜一遍,但那样是找不出答案的,应该是在搜索中找到一次后就再从头在没有被选的木棍里去凑目标长度。

代码:

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

int n;
int stick[65];
int visit[65];
int flag;

bool comp(int a, int b) {
	return a > b;
}
void DFS(int target,int len,int num,int pos) {//target目标长度,len凑的长度,num是选中的木棍数,pos是当前木棍是第几个木棍
	if (flag)return;
	if (num == n) {
		flag = 1;
		return;
	}
	for (int i = pos; i < n; i++) {
		if (!visit[i]&&stick[i] + len <= target) {
			visit[i] = 1;
			if (stick[i] + len == target) {			//满足目标长度后在从第一个木棍开始往后搜
				DFS(target, 0, num + 1, 0);
			}
			else {
				DFS(target, len + stick[i], num + 1, i+1);
			}
			
			visit[i] = 0;
			if (flag)return;		//满足就退出
			if (len == 0)return;	//剪枝,将所有可选的木棍扫一遍后发现没有可以选进来的就说明该target不可行,对于为什么len等于0,可以看一下if语句的DFS自己理解一下。
			while (i < n&&stick[i + 1] == stick[i])i++;
		}
	}
}
int main() {
	while (cin >> n&&n) {
		int sum = 0;
		for (int i = 0; i < n; i++) {
			cin >> stick[i];
			sum += stick[i];
		}
		flag = 0;
		memset(visit, 0, sizeof(visit));
		sort(stick, stick + n, comp);			//排序的目的一是找最长的木棍方便,二是在DFS中剪枝方便,具体看DFS函数的while循环
		for (int i = stick[0]; i <= sum; i++) {		//枚举木棍最小可能长度,范围是所有木棍中最长的那个到所有木棍长度之和
			if (i == sum) { cout << sum << endl; break; }
			else if (sum%i == 0) {
				DFS(i,0,0,0);
			}
			if (flag) {
				cout << i << endl;
				break;
			}
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值