POJ1011 Sticks

POJ1011 Sticks

时间限制: 1 Sec  内存限制: 128 MB
提交: 43  解决: 8
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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.

 

输入
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.
 

 

输出
The output should contains the smallest possible length of original sticks, one per line.

 

样例输入

复制样例数据

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
样例输出
6
5


搜索剪枝

#include "bits/stdc++.h"

using namespace std;
const int maxn = 100;

int s[maxn];
int vis[maxn];

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

int num, len;
int n;


bool dfs(int done, int now, int last) {
    if (done >= num) return true;
    if (now == len) return dfs(done + 1, 0, 1);
    int fail = 0;//剪枝1:不重复插入上一个失败的木棍长度
    for (int i = last; i <= n; i++) {
        //剪枝2:构造一根原始木棍时按递减插入,
        // 因为先插入x后插入y和先插入y后插入x是一样的
        if (!vis[i] && now + s[i] <= len && s[i] != fail) {
            vis[i] = 1;
            if (dfs(done, now + s[i], i + 1)) return true;
            vis[i] = 0;
            fail = s[i];
            if (now == 0 || now + s[i] == len) return false;
            //剪枝3,4.如果当前木棍是0或当前木棍以拼成功,却失败了,则说明无解
        }
    }
    return false;
}

int main() {
    freopen("input.txt", "r", stdin);
    while (scanf("%d", &n)) {
        if (n == 0) break;
        int to = 0;
        int maxx = 0;
        for (int i = 1; i <= n; i++) {
            scanf("%d", &s[i]);
            to += s[i];
            maxx = max(maxx, s[i]);
        }
        sort(s + 1, s + 1 + n, cmp);
        for (int i = maxx; i <= to; i++) {
            if (to % i == 0) {
                len = i;
                num = to / i;
                memset(vis, 0, sizeof(vis));
                if (dfs(0, 0, 1)) {
                    printf("%d\n", i);
                    break;
                }
            }
        }
    }
    return 0;
}

 

posted @ 2019-03-07 22:53 Albert_liu 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值