Square poj2362深度优先搜索+剪枝

探讨如何使用DFS+剪枝算法解决正方形拼接问题,通过合理排序和剪枝策略提高求解效率。

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

1.题目原文

Square
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 24028 Accepted: 8300

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

Source

2.解题思路

DFS+剪枝

给定一堆不定长度的小棒子,问他们能否构成一个正方形。

 

解题思路:

POJ1011的热身题,DFS+剪枝

 

本题大致做法就是对所有小棒子长度求和sum,sum就是正方形的周长,sum/4就是边长side。

问题就转变为:这堆小棒子能否刚好组合成为4根长度均为side的大棒子

 

不难了解,小棒子的长度越长,其灵活性越差。例如长度为5的一根棒子的组合方式要比5根长度为1的棒子的组合方式少,这就是灵活性的体现。

由此,我们首先要对这堆小棒子降序排序,从最长的棒子开始进行DFS

 

剪枝,有3处可剪:

1、  要组合为正方形,必须满足sum%4==0;

2、  所有小棒子中最长的一根,必须满足Max_length <= side,这是因为小棒子不能折断;

3、  当满足条件1、2时,只需要能组合3条边,就能确定这堆棒子可以组合为正方形。

3.AC代码

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

#define maxn 25

int n;
int a[maxn];
bool mark[maxn];

int side;
int sum;

int cmp(const void* a,const void* b)//降序
{
    return *(int*)b-*(int*)a;
}

bool dfs(int num,int len,int s)
{
    //num是已组合的正方形的边数,len是当前组合边已组合的长度,len<=side,s是数组a[i]搜索的起点
    if(num==3){////剪枝3,当满足剪枝1和2的要求时,只需组合3条side,剩下的棒子必然能够组成最后一条side  
        return true;
    }
    for(int i=s;i<n;i++){
        if(mark[i]){
            continue;
        }
        mark[i]=true;
        if(len+a[i]<side){
            if(dfs(num,len+a[i],i))
                return true;
        }
        else if(len+a[i]==side){
            if(dfs(num+1,0,0))
                return true;
        }
        mark[i]=false;
    }
    return false;
}

void solve()
{
    memset(mark,0,sizeof(mark));
    sum=0;
    for(int i=0;i<n;i++){
        sum+=a[i];
    }
    if(n<3||(sum%4!=0)){//剪枝1,不能构成正方形
        cout<<"no"<<endl;
        return;
    }
    side=sum/4;
    qsort(a,n,sizeof(int),cmp);//降序排列,先组合长棒,因为长棒相对于短棒的组合灵活性较低
    if(side<a[0]){//剪枝2,最长边大于正方形边长
        cout<<"no"<<endl;
        return;
    }
    if(dfs(0,0,0)){
        cout<<"yes"<<endl;
        return;
    }
    else{
        cout<<"no"<<endl;
        return;
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
        solve();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值