Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1292735
  • 博文数量: 196
  • 博客积分: 4141
  • 博客等级: 中将
  • 技术积分: 2253
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-21 20:04
文章存档

2019年(31)

2016年(1)

2014年(16)

2011年(8)

2010年(25)

2009年(115)

分类:

2009-06-18 10:30:00

Square

Time Limit:1sMemory limit:32M
Accepted Submit:175Total Submit:839

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 <cstdio>
#include <cstdlib>
#include <algorithm>

using namespace std;

int flag;
int nums;
int sum = 0;
int sticks[30];
int used;
int stack[100];
int top;

int square(int v, int s, int n)
{
    int i;

    if (s == sum && n == 4)
    {
        flag = 1;
        return 0;
    }

    if (s == sum)
    {
        v = 0;
        s = 0;
        ++n;
        for (i = 0; i < top; ++i)
            if (stack[i] == used)
                return 0;
        stack[top++] = used;
    }

    if (v >= nums)
        return 0;

    for (i = v; i < nums && !flag; ++i)
    {
        if (s + sticks[i] <= sum)
        {
            if ((used & (1 << (i))) == 0)
            {
                used |= (1 << (i));
                square(i + 1, s + sticks[i], n);
                used &= ~(1 << (i));
                if (s == 0)
                    break;
            }
        }
    }

    return 0;
}

int main()
{
    int i, num, j, tmp, k;

    scanf("%d", &num);
    for (k = 1; k <= num; ++k)
    {
        scanf("%d", &nums);
        sum = 0;
        flag = 0;
        used = 0;
        top = 0;
        for (j = 0; j < nums; ++j)
        {
            scanf("%d", &sticks[j]);
            sum += sticks[j];
        }
        for (i = 1; i < nums; ++i)
        {
            for (j = 0; j < i; ++j)
            {
                if (sticks[i] > sticks[j])
                {
                    tmp = sticks[j];
                    sticks[j] = sticks[i];
                    sticks[i] = tmp;
                }
            }
        }
        if ((sum & 0x3) || (sticks[0] > (sum >> 2)) || (num < 4))
            printf("no\n");
        else
        {
            sum >>= 2;

            used |= 1;
            square(1, sticks[0], 1);
            if (flag)
                printf("yes\n");
            else
                printf("no\n");
        }
    }

    return 0;
}

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