hdu 1518 Square 【dfs】

本文探讨了一道经典的算法题目,即如何通过给定长度的棍子组合形成一个正方形。文章提供了详细的分析思路和完整的代码实现,采用深度优先搜索算法进行求解,并通过实例演示了算法的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1518

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19311    Accepted Submission(s): 6067


 

Problem 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

题意:对于输入的m个数,经过一番整合(可以数相加),只要能够成正方形,就输出yes,否则输出no.

分析:深搜,终止条件是num==4,如果这一条件成立,则输出yes,否则输出no.

代码如下:

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn = 101;
int a[maxn],vis[maxn],n,sum,flag,psum;
void DFS(int num,int len,int pos)
{
    if(num == 4) //因为是判断能不能够成正方形,所以若是=4,直接return
    {
        flag = 1;
        return ;
    }
    if(len == psum) //等于平均值,则说明有一个符合题意了,len和对应的pos重新置为0
    {
        DFS(num+1,0,0);
        if(flag)
            return;
    }
    for(int i=pos;i<n;i++) //遍历每一种可能的情况,初始情况pos为0
    {
       if(!vis[i] && len + a[i] <= psum)
       {
           vis[i] = 1;
           DFS(num,a[i]+len,i+1);
           if(flag)
               return;
           vis[i] = 0; //回溯操作
       }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        memset(vis,0,sizeof vis);
        sum = 0;
        flag = 0;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            sum += a[i];
        }
        if(sum%4 != 0) //不能被4整除,一定不能,相当于剪枝
        {
            puts("no");
            continue;
        }
        psum = sum/4;
        for(int i=0;i<n;i++)
        {
            if(a[i] > psum) //这个符合的话,肯定就不可能满足了
            {
                flag = 1;
                break;
            }
        }
        if(flag == 1)
        {
            puts("no");
            continue;
        }
        DFS(0,0,0);
        if(flag == 1)
            puts("yes");
        else
            puts("no");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值