码迷,mamicode.com
首页 > 其他好文 > 详细

poj1011Sticks 经典搜索

时间:2015-07-29 21:30:00      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:搜索

//给n个小木棒,拼成任意个长度相等的长木棒
//求长木棒的最短长度
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std ;
const int maxn = 110 ;
int a[maxn] ;
int vis[maxn] ;
int num , len ,n  ;
bool dfs(int sum , int pos , int cnt)
{
    if(cnt == num)return true ;
    if(sum == len)return dfs(0 , 1 , cnt + 1) ;
    int pre = 0 ;
    for(int i = pos ;i <= n ;i++)
    {
        if(vis[i])continue ;
        if(sum + a[i] <= len)
        {
            vis[i] = 1 ;
            if(dfs(sum + a[i] , pos + 1 ,cnt))
            return true ;
            vis[i] = 0 ;
            if(a[i] + sum == len)return false;//如果这次已经能将这根木棒拼好,但是后面的失败,那么后面的就不用考虑
            if(sum == 0)return false;  //如果第一次没有拼好,那么后面也不会拼好
            while(a[i] == a[i+1])i++; //如果这次没有拼好,那么这次可以直接跳过和这次一样的小木棒
        }
    }
    return false ;
}
bool cmp(int a , int b)
{
    return a > b ;
}
int main()
{
    //freopen("in.txt","r",stdin);
    while(scanf("%d" , &n)&&n)
    {
        int sum = 0 ;
        int ma = 0 ;int ans = 0;
        for(int i = 1;i <= n;i++)
        {
            scanf("%d" , &a[i]) ;
            ma = max(ma , a[i]) ;
            sum += a[i];
        }
        sort(a + 1 , a + 1 + n , cmp);
        for(int i = ma ;i <=sum;i++)
        if(sum % i == 0 && i >= ma)
        {
            memset(vis , 0 , sizeof(vis)) ;
            num = sum/i ;
            len = i ;
            if(dfs(0 , 1 , 0))
            {
                ans = i ;
                break;
            }
        }
        cout<<ans<<endl;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

poj1011Sticks 经典搜索

标签:搜索

原文地址:http://blog.csdn.net/cq_pf/article/details/47132513

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!