Square HDU - 1518

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

给出几条线段,判断是否能组成一个正方形。
可以知道边长是总长的1/4,先将线段从大到小排序,每层取一条,放得下则下层再从比它小的线段找,避免重复,组成一条边后清零,从头在没有取走的继续找,直到组成三条,剩下必定能组成第四条。

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int vis[30];
int a[30];
int q,n;
bool ss(int cot,int i,int len){
    if(cot==3){
        return true;
    }else{
        for(int j=i;j<n;j++){
            if(!vis[j]){
                if(a[j]==len){
                    vis[j]=1;
                    if(ss(cot+1,0,q)){
                        return true;
                    }
                }else if(a[j]<len){
                    vis[j]=1;
                    if(ss(cot,j+1,len-a[j])){
                        return true;
                    }
                }
                vis[j]=0;
            }
        }
    }
    return false;
}
int main()
{
    int T,i,s;

    cin>>T;
    while(T--){
        cin>>n;
        s=0;
        memset(vis,0,sizeof(vis));
        for(i=0;i<n;i++){
            cin>>a[i];
            s+=a[i];
        }
        sort(a,a+n);
        if(s%4!=0){
            cout<<"no"<<endl;
        }else{
            q=s/4;
            if(ss(0,0,q)){
                cout<<"yes"<<endl;
            }else{
                cout<<"no"<<endl;
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值