hdu 1518 Square【DFS+剪枝】

Square

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12104    Accepted Submission(s): 3856


Problem Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
 

Input
The first line of input contains N, the number of test cases. Each test case begins with an integer 4 <= M <= 20, the number of sticks. M integers follow; each gives the length of a stick - an integer between 1 and 10,000.
 

Output
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
Sample Input
3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
 


Sample Output
yes
no
yes
 

 

这个题大概调试+剪枝+优化算法整整用了两个多小时,怎么写都是TLE,后来在网上大牛那里学到一个对于DFS来说一个会很常用的剪枝方式。

思路:

对于n个小木棍要组成一个正方形,那么每条边都是想同的,那么如果所有木棍长度加和/4不是整数的话,说明这些小木棍全部都要使用上是一定不可能组成正方形的。那么对于可能能够组成正方形的情况,我们每一条边都一定是sum/4的长度。

所以我们这样dfs:用变量len表示当前小木棍组成的长度,用cont表示当前组好了多少根小木棍。如果len==sum/4,辣么cont+1,否则继续在len上添加新成员。

这时候第一个出现的可以很简单就搞定的剪枝:if(a【i】+len>sum/4)continue;

有了一个正确的思路,剩下的就是调试和敲代码了、欢欢喜喜的敲完,TLE。

辣么要怎样才能不TLE呢?我这里算是学到一个新的剪枝小技巧,在dfs的过程中,我们用一个变量k标记从哪根小木棍开始选取,这样我们不用从0开始遍历而是从k开始遍历,是会节省很多很多步骤的。

我们对应AC代码来学习这个k的妙用:

#include<stdio.h>
#include<string.h>
using namespace std;
int a[105];
int vis[105];
int ok;
int n;
int averge;
void dfs(int cont,int len,int k)
{
    if(cont==4)//如果达到目的,标记并返回。
    {
        ok=1;
        return ;
    }
    if(len==averge)//如果当前木棍长度达到了sum/4,那么进行下一根小木棍的拼接。
    {
        dfs(cont+1,0,0);//这块注意我们需要将k变成0,因为之前vis[i](i<k)还有没有选取到的小木棍。
        if(ok==1)return ;
    }
    for(int i=k;i<n;i++)
    {
        if(vis[i]==0&&len+a[i]<=averge)
        {
            vis[i]=1;
            dfs(cont,a[i]+len,i+1);//这里dfs的是i+1,很简单就可以解释:如果之前的i选取过了,那么也不需要再选取了,如果之前的i我们选择不取 ,那么之后也不需要取,至于之后为什么不取,是因为len+a[i]>averge了呗0.0,辣么之后也不需要这个i,所以之后也不需要这个i。
            if(ok==1)return ;
            vis[i]=0;
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(vis,0,sizeof(vis));
        scanf("%d",&n);
        int sum=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        int i;
        if(sum%4!=0)
        {
            printf("no\n");
            continue;
        }
        else
        {
            averge=sum/4;
            ok=0;
            dfs(0,0,0);
            if(ok==0)printf("no\n");
            else printf("yes\n");
        }
    }
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值