hdu 1518(深搜)

本文探讨了使用不同长度的木棒是否能拼成正方形的问题,并提供了一种通过深度优先搜索(DFS)来解决该问题的方法。文章首先检查所有木棒的总长度是否能被4整除,接着通过递归调用DFS来尝试组合成四条相等边长的木棒。

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

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

Square

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


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

题意:给你n根木棒,然后问这些木棒首尾相连能不能构成一个正方形;(注意:n个木棒必须全部用完不能有剩余)

思路:要想用这n根木棒形成一个正方形,如果n根木棒的总长度sum不能整除4或者n<4那么指定不能形成正方形,否则cnt=sum/4; 

           接下来DFS()看这n根木棒能否组成4根长度为cnt的木棒;

//剪支62MSAC
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;

int n,cnt,sum;

struct node
{
  int lenth;
  int mark;
}stick[25];

int cmp(node a,node b)
{
    return a.lenth>b.lenth;
}

int dfs(int len,int count,int l,int pos)
{
   if(count==4)return 1;
   for(int i=pos;i<n;i++)
   {
       if(stick[i].mark)continue;
       
       if(len==(stick[i].lenth+l))
        {
          stick[i].mark=1;
          if(dfs(len,count+1,0,0))
                return 1;
          stick[i].mark=0;
          return 0;
        }
       else if(len>(stick[i].lenth+l))
        {
           stick[i].mark=1;
           l+=stick[i].lenth;
           if(dfs(len,count,l,i+1))
                return 1;
           l-=stick[i].lenth;
           stick[i].mark=0;
           if(l==0) return 0;
           while(stick[i].lenth==stick[i+1].lenth)i++;
        }
   }
   return 0;
}
int main()
{
        int T;
        cin>>T;
        while(T--)
        {
           scanf("%d",&n);
           cnt=sum=0;
           for(int i=0;i<n;i++)
            {
                scanf("%d",&stick[i].lenth);
                sum+=stick[i].lenth;
                stick[i].mark=0;
            }
           sort(stick,stick+n,cmp);
           if(sum%4||n<4)
           {
               cout<<"no"<<endl;
               continue;
           }
           cnt=sum/4;
           if(dfs(cnt,0,0,0))
           {
               cout<<"yes"<<endl;
           }
           else
           {
               cout<<"no"<<endl;
           }
        }
        return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值