CSU-ACM2017暑期训练4-dfs G - Sticks HDU - 1455

题目:

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

           题意:给你一串数字,将他们中的有些数字相加,得到另一串数字他们的值全为k,求这个k的最小值。

           思路:显然k的范围是这串数字的最大值到这串数字的总和,然后对这个值进行判断,看这串数字能不能通过变换使其全为k。这里用到搜索。这题搜索的时候需要用剪枝的地方特别多,不然很容易超时,具体见代码。


代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 100;

int a[66],vis[66];
int T,n,m;
int sum,len,flag,tot,can;

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

void dfs(int res,int step,int pos)//res:要凑齐tot还需要的数量.setp:搜索过的木棍总数.pos:当前搜索到的位置
{
    if(flag)//标记成功与否
        return;
    if(step==n)
    {
        flag=1;
        return;
    }
    if(res==0&&step<n)
        dfs(tot,step,0);
    for(int i=pos;i<n;i++)
    {
        if(!vis[i]&&!flag&&a[i]<=res)
        {
            vis[i]=1;
            dfs(res-a[i],step+1,i+1);
            vis[i]=0;
            if(res==tot)//第1次剪枝:如果剩下的res还有tot这么长说明最大的木棍也就是当前这根不能用,直接停止搜索
                return;
            while(a[i]==a[i+1])//第2次剪枝:如果下一次搜到的和这一次一样,则直接跳过.
                  i++;
        }
    }
}

int main()
{
	while(scanf("%d",&n)!=EOF&&n)
    {
        sum=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        sort(a,a+n,cmp);
        for(int i=a[0];i<=sum;i++)
        {
            if(sum%i)
                continue;
            memset(vis,0,sizeof(vis));
            flag=0;
            tot=i;
            dfs(tot,0,0);
            if(flag)
            {
                printf("%d\n",i);
                break;
            }
        }
    }
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值