FJUT 2801 square depth-first search of the garbage man pruning +

Garbage guy square
TimeLimit: 4000ms the MemoryLimit: 128MB
64-bit Integer-IO format:% LLD
Problem the Description
garbage man recently came across a simple question.

Given a set of sticks and asked if they can make up a square end to end (stick need run out).

Because too easy, too lazy to do the garbage guy, so throw garbage guys put this question to you.

Input
first line a positive integer T, represents a number (T <= 41) set of test data. Solution down each row starts with a positive integer N (4 <= N <= 20), indicates the number of the stick, followed by the positive integer number N (X1, X2, X3 ... Xn ), Xi represents the length of a stick, ( 1 <= Xi <= 10,000) .

Output
For each test, configured as a square if possible, outputs a "yes", and otherwise outputs "no".

SampleInput
3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
SampleOutput
yes
no
yes

Meaning of the questions: you asked whether the n stick to form a square with all stick
ideas: deep pruning search +

#include <stdio.h>
#include <algorithm>
#include <string.h>

using namespace std;

int a[30];
bool vis[30];

int sum,num,n ;

bool cmp(int a,int b)
{
    return a > b;
}

bool dfs(int num,int len,int st)///已经构成边的数目  当前边的长度 添加边的起点
{
    if(num == 3)///构成三条边则另一条边已经固定直接返回成功构成
        return true;

    for(int i = st ;i < n;i ++)
    {
        if(vis[i])
            continue;

        vis[i] = true;

        if(len+a[i]<sum)///一条边还没构成继续构成改边
        {
            if(dfs(num,len+a[i],i+1))
                return true;
        }
        else if(len+a[i] == sum)///成功构成一条边
        {
            if(dfs(num+1,0,0))
                return true;
        }

        vis[i] = false;///还原该边
    }
    return false;
}

int main()
{
    int t;

    scanf("%d",&t);

    while(t--)
    {
        scanf("%d",&n);
        sum = 0;
        num = 0;

        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }

        if(sum%4)///如果周长不是4的倍数直接无法构成
        {
            printf("no\n");
            continue;
        }

        sort(a,a+n,cmp);///升序排序 更长的木棍可选择的条件较少 应该优先处理

        sum/=4;

        if(a[0]>sum)///如果有最长的木棍比一条边还长也无法构成
        {
            printf("no\n");
            continue;
        }

        memset(vis,0,sizeof(vis));

        if(dfs(0,0,0))
            printf("yes\n");
        else
            printf("no\n");
    }
    return 0;
}
Published 54 original articles · won praise 0 · Views 1213

Guess you like

Origin blog.csdn.net/weixin_44144278/article/details/102698238