HDU -1518 Square 神搜给力啊!

Square

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


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
 


这题刚看时完全没思路,后来也是在膜拜了各路大神之后才恍然大悟了,这题关键还是在于深搜函数的设计,仔细结合注释看看吧

#include<stdio.h>
#include<stdlib.h>
int vis[25],a[25];
int sum,edge,m;
/*
# start 代表搜索数组a的起始位置
# current_length 代表当前匹配的边长长度
# cur  代表当前完成的匹配边数
*/
int dfs(int start,int current_length,int cur){
    int i;
    if(current_length==edge)
    {//每组成一条边则判断当前组成边数是否为三,如果不为三则进行下一边长的深度匹配
        return cur==3?1:dfs(0,0,cur+1);
    }
    else
    {//当前边长如果小于正方形边长edge则继续进行深度匹配
        for(i=start;i<m;i++)
        {
            if(!vis[i]&&current_length+a[i]<=edge)
            {//访问当前棒长并判断当前匹配长度是否达到正方形边长
                vis[i]=1;//将当前访问的位置标记,防止用过的棒再次被用
                if(dfs(i+1,current_length+a[i],cur))
                return 1;//表示当前边匹配成功
                vis[i]=0;//访问过的位置重新标记为零,方便下次搜索
            }//if
        }//for
    }//else
    return 0;
}//dfs
int main()
{
    int n,i,max;
    scanf("%d",&n);//测试样例组数
    while(n--){
        scanf("%d",&m);
        max=0;//跟踪输入的最大棒长度
        sum=0;
        memset(vis,0,sizeof(vis));
        for(i=0;i<m;i++)
        {
            scanf("%d",&a[i]);
            max=max>a[i]?max:a[i];
            sum+=a[i];
        }//for
        //printf("%d %d\n",sum,max);
        if(sum%4||max>sum/4)//长度和不是4的倍数或最大棒长大于平均边长
        printf("no\n");
        else
        {
            edge=sum/4;
            if(dfs(0,0,1))
            printf("yes\n");//匹配成功
            else printf("no\n");
        }//else
    }//while
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值