浙江财经大学
信工学院ACM集训队

POJ 1011 Sticks

本文由 Ocrosoft 于 2016-10-31 17:05:51 发表
Sticks

Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%lld & %llu

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 should 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

Solution

经典的DFS题,里面的剪枝变态啊,想不到啊…
题意:给出一堆木棒,将这些木棒组合成 若干根 相同长度的 木棒,要求长度最短。
思路:组合显然不能瞎组合,目标长度一定在 最长的那根长度 到 所有木棒的长度和 之间,dfs的时候组合木棒长度到了这个就开始组下一根,如果
总根数=sum(长度和)/L(目标长度),就说明找到了答案。具体的看代码比较好…

#include <set>
#include <map>
#include <list>
#include <cmath>
#include <stack>
#include <queue>
#include <ctime>
#include <string>
#include <cstdio>
#include <vector>
#include <cctype>
#include <climits>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
#define strend string::npos
#define ms(a) memset(a,0,sizeof(a))
typedef long long LL;
const LL LINF = LLONG_MAX / 2;
const int INF = INT_MAX / 2;
const int MAXN = 64 + 10;
const int MOD = 1000000009;
int gcd(int a, int b)
{
	if (!b)return a;
	return gcd(b, a%b);
}
using namespace std;
//or2..or2..or2..or2..//
int n, sticks[MAXN], sum, tot, tar;
bool use[MAXN], flag;
//当前已组成木棒数,当前正在组成的木棒长度,当前使用的木棒位置
bool dfs(int sm,int len,int pos)
{
	if (sm == tot)return true;//恰好组成tot根木棒
	for (int i = pos + 1; i < n; i++)
	{
		if (use[i])continue;
		if (len + sticks[i] == tar)//成功组成一根
		{
			use[i] = true;
			if (dfs(sm + 1, 0, -1))return true;//接下来的也成功
			use[i] = false;//接下来的失败
			return false;
		}
		else if(len+sticks[i]<tar)//大于tar的跳过不考虑
		{
			use[i] = true;
			if (dfs(sm, len + sticks[i], i))return true;
			use[i] = false;
			if (!len)return false;
			while (sticks[i] == sticks[i + 1])i++;
		}
	}
	return false;
}
int main()
{
	while (cin >> n && n)
	{
		ms(use), flag = sum = tot = tar = 0;//init
		for (int i = 0; i < n; i++)
			cin >> sticks[i], sum += sticks[i];
		sort(sticks, sticks + n, greater<int>());
		for (tar = sticks[0]; tar <= sum; tar++)
		{
			if (sum%tar)continue;
			tot = sum / tar;
			if (dfs(1, 0, -1)) { printf("%d\n", tar); break; }
		}
	}
	return 0;
}

欢迎转载,请保留出处与链接。Ocrosoft » POJ 1011 Sticks

点赞 (0)or拍砖 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址