poj1011 dfs

传送门
汉语题不解释

#include <set>
#include <map>
#include <stack>
#include <queue>
#include <math.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <algorithm>

using namespace std;
typedef long long LL;
const int MAXN = 70;
const double PI = acos(-1);
const double eps = 1e-8;
const int MOD = 1e9+7;
const int INF=0x3f3f3f3f;
/**
合并后的木棍的长度肯定是大于等于最长的那根木棍长度的。而且时求最小的合并长度所以
所以我们从最长的木棍 向上枚举 合并后的木棍的长度值。
设所有木棍长度为sum,合并后的木棍长度为B,那么必须满足
sum%B==0,才能进行搜索查找,当满足sum%B==0 时,次 此时最多
拼处sum/B根木棍,那么我们用搜索找出是否可行,用flag标记是否可行
令num=sum/B,表示需要合并的木棍数
*/
int len[MAXN];///len[i] 表示长度为i的木棍的个数
int flag,B;///B 是合并后的木棍长度
/// num表示剩余需要合并的木棍个数
/// rest表示还差rest长度  合并木棍长度到达B 长度
/// mlen表示下一个用来合并进入rest的木棍长度
void check(int num,int rest,int mlen)
{
    if(num==0||flag)///当num==0时,合并完了所有木棍
    {
        flag=1;
        return;
    }
    int i;
    if(!flag)///没有合并完
    {
        len[mlen]--;///长度为mlen的木棍个数减1,用掉这根木棍
        rest-=mlen;
        if(rest>0)///rest>0说明还差rest长度合并成长度为B的木棍
        {
            for(i=rest; i>=1; i--)///枚举木棍长度
            {
                if(len[i])///长度为i的木棍个数大于0个,可以用来合并,搜一下试试
                    check(num,rest,i);
            }
        }
        else///rest==0的情况,说明当前木棍合并完成
        {
            for( i=50; i>=1; i--)///最长的木棍小于50,
            {
                if(len[i])///找到现存的最长的木棍
                    break;
            }
            check(num-1,B,i);///搜索下一根木棍,所以num-1,下一根木棍长度依然是B;
                               /// i:把现存的最长的木棍 利用进去
        }
        len[mlen]++;///回溯时把长度为mlen的木棍个数加回来,回溯的意思就是刚刚 用的木棍现在不用了,所以加回来
    }
}
int main()
{
    int n,val,mlen,sum;
    while(scanf("%d",&n)!=-1)
    {
        if(n==0)
            break;
        memset(len,0,sizeof(len));
        sum=0;
        mlen=-9;
        for(int i=0; i<n; i++)
        {
            scanf("%d",&val);
            len[val]++;
            if(val>mlen)
                mlen=val;///求最大值
            sum+=val;///求和
        }
        flag=0;
        B=mlen;///合并后的木棍长度值初始值为木棍长度的最大值
        while(1)
        {
            if(sum%B==0)
            {
                check(sum/B,B,mlen);
                if(flag)
                    break;
            }
            B++;
        }
        cout<<B<<endl;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值