洛谷——P2383 狗哥玩木棒

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了洛谷——P2383 狗哥玩木棒相关的知识,希望对你有一定的参考价值。

P2383 狗哥玩木棒

题目背景

狗哥又趁着语文课干些无聊的事了...

题目描述

现给出一些木棒长度,那么狗哥能否用给出的木棒(木棒全用完)组成一个正方形呢?

输入输出格式

输入格式:

 

输入文件中的第一行是一个整数n表示测试的组数,接下来n行表示每组的测试数据。 每行的第一个数为m(4<=m<=20),接下来m个数ai(1<=ai<=1000)表示木棒的长度。

 

输出格式:

 

对于每组测试数据,如果可以组成正方形输出“yes”,否则输出“no”。

 

输入输出样例

输入样例#1:
3
4 1 1 1 1 
5 10 20 30 40 50 
8 1 7 2 6 4 4 3 5
输出样例#1:
yes
no
yes

说明

狗哥快抓狂了

 

搜索+特判

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define N 100
using namespace std;
bool flag;
int Q,n,a[N],tot,p[5];
int cmp(int a,int b){return a>b;}
int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<0||ch>9){if(ch==0)f=-1;ch=getchar();}
    while(ch>=0&&ch<=9) x=x*10+ch-0,ch=getchar();
    return x*f;
}
void dfs(int x)
{
    if(flag) return ;
    if(x==n+1)
    {
        flag=1;
        return ;
    }
    for(int i=1;i<=4;i++)
    {
        if(a[x]>p[i]) continue;
        p[i]-=a[x];
        dfs(x+1);
        p[i]+=a[x];
    }
}
int main()
{
    Q=read();
    while(Q--)
    {
        n=read(),tot=0;
        for(int i=1;i<=n;i++) a[i]=read(),tot+=a[i];
        if(tot%4!=0) {printf("no\n"); continue;}
        sort(a+1,a+1+n,cmp);
        if(a[1]>tot/4) {printf("no\n"); continue;}
        for(int i=1;i<=4;i++) p[i]=tot/4;
        flag=false;dfs(1);
        if(flag) printf("yes\n");
        else printf("no\n");
    }
    return 0;
}

 

以上是关于洛谷——P2383 狗哥玩木棒的主要内容,如果未能解决你的问题,请参考以下文章

洛谷 P2383 狗哥玩木棒

洛谷——P2383 狗哥玩木棒

P2383 狗哥玩木棒

关于两道搜索的题目

Luo2383:狗哥玩木棒 题解

搜索专题练习