HDU--杭电--1518--Square--深度优先搜索--这个不是水题了

Square

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


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 <iostream>
#include <algorithm>
using namespace
std;
int
n,s,k,a[22],visit[22]={0};  //a数组用来记录那一组数据,visit数组用来记录当前组的数据是否可用
void
DFS(int sum,int x,int d)  //sum是当前计算的和,等于正方形边长的话就配好了一条边了,x是记录当前配好了多少条边,d是上一次匹配到了哪里,是剪枝的关键
{

    if
(
k||x==3)  //当配上了三边的时候就说明能构成正方形了,如果已经能配成正方形就直接返回了
    {

        k=1;return;  //k=1标记已经能够成正方形了
    }

    int
i;
    for
(
i=d;i<n;i++)  //从上次断点开始匹配
    {

        if
(
k)return;  //已经构成正方形就直接返回
        if
(!
visit[i])  //询问这第i组数据是否可用
        if
(
sum+a[i]==s)  //如果正好配成边
        {

            visit[i]=1;
            DFS(0,x+1,0);  //初始化s和d并已经配成的边+1
            visit[i]=0;
        }

        else if
(
sum+a[i]<s)  //如果比边小
        {

            visit[i]=1;
            DFS(sum+a[i],x,i+1);  //传送断点和此时的值
            visit[i]=0;
        }
    }
}

bool
cmp(int a,int b)
{

    return
a<b;
}

int
main(void)
{

    int
m,i;
    cin>>m;
    while
(
m--&&cin>>n)
    {

        for
(
i=s=0;i<n;i++)
            cin>>a[i],s+=a[i];  //统计正方形周长
        sort(a,a+n,cmp);  //从小到大排序
        if
(
s%4==0)  //判断周长是否是正方形的形式
        {

            s/=4;  //s变成记录正方形的边长
            k=0;  //初始化k
            DFS(0,0,0);  //和为0,已配成的边数量为0,断点是起点
            if
(
k)cout<<"yes"<<endl;
            else
cout<<"no"<<endl;
        }

        else
cout<<"no"<<endl;
    }

    return
0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值