Chinaunix首页 | 论坛 | 博客
  • 博客访问: 343588
  • 博文数量: 122
  • 博客积分: 5000
  • 博客等级: 大校
  • 技术积分: 1191
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-24 11:12
文章分类

全部博文(122)

文章存档

2010年(122)

我的朋友

分类: C/C++

2010-03-19 16:42:52

 

资料来源:http://brightstar.cublog.cn/

 

一、问题描述

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

 

二、解题思路

解题思路来源于:http://www.cppblog.com/jhpjhyx/archive/2009/05/14/82981.html 在此表示感谢!

三、代码

 

#include<iostream>
#include<algorithm>
using namespace std;
int N;//木块数量

int L[21];//每块木块的长度

int len;//形成正方形的边长

int s;//所有木块长度

bool used[21];
int cmp(const void * a,const void *b)
{
    return *(int *)b - *(int *)a;
}
bool find(int setnum,int depth,int sum=0)
{
    if(setnum ==1)
        return true;
    for(int i=depth;i<=N;++i)
    {
        if(used[i]==true)
            continue;
        if (i>1 && !L[i - 1] && L[i] == L[i-1])
        continue;
        int sum_now=L[i]+sum;
        if(sum_now < len)
        {
            used[i]=true;
            if(find(setnum,i+1,sum_now))
                return true;
            used[i]=false;
        }
        else
            if(sum_now==len)
            {
                used[i]=true;
                if(find(setnum-1,1,0))
                    return true;
                used[i]=false;
            }
            if(sum_now==len || sum ==0)
                break;
    }
    return false;
}
int main()
{
    int i,j,t;
    int MAX;
    cin>>t;
    for(i=1;i<=t;++i)
    {
        cin>>N;
        s=0;
        MAX=0;
        for(j=1;j<=N;++j)
        {
            cin>>L[j];
            s+=L[j];
            used[j]=false;//设置为未使用

            if(L[j]>MAX)
                MAX=L[j];//考虑单个L[j]>Len

        }
        if(s%4!=0)//总和不能被4整除

        {
            cout<<"no"<<endl;
            continue;
        }
        else
            len=s/4;
        if(MAX>len)//最大的数不有大于边长

        {
            cout<<"no"<<endl;
            continue;
        }
        qsort(L+1,N,sizeof(int),cmp);
        if(find(4,1,0))
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
    return 0;
}


阅读(1384) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~