AcWing 167. 木棒

分析

在这里插入图片描述

代码

#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int N=70;
bool st[N];
int n;
int w[N];
int len;
int sum;
bool dfs(int u,int cnt,int start){
    if(u*len==sum)return true;//如果所有的木棒全部组成完了,就return true
    if(cnt==len)return dfs(u+1,0,0);//如果当前的木棒全部组成完了,就return true
    for(int i=start;i<n;i++){
        if(st[i])continue;
        if(w[i]+cnt>len)continue;
        st[i]=true;
        if(dfs(u,cnt+w[i],i+1))return true;
        st[i]=false;
        if(!cnt||cnt+w[i]==len)return false;//第一个木棍或者最后一个木棍组成失败了,就失败了
        int j=i;
        while(j<n&&w[j]==w[i])j++;//如果第i个木棍失败了,那么和该木棍等长的木棍也失败,所以直接略去
        i=j-1;
    }
    return false;
}
int main(){
    while(cin >> n,n){
        memset(st,false,sizeof st);
        sum=0;
        len=0;
        for(int i=0;i<n;i++){
            cin >> w[i];
            sum+=w[i];
        }
        sort(w, w + n);//从小到大排序,减小分支
        reverse(w, w + n);
        len=w[0];//len从所有木棍里最大长度开始枚举
        while(len){
            if(sum % len == 0&&dfs(0,0,0)){//如果枚举长度是总长度的因子时才有可能成功
                cout << len <<"\n";
                break;
            }
            len++;
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值