回溯法Square

 

Square

Description

Given a set ofsticks of various lengths, is it possible to join them end-to-end to form asquare?

Input

The first line ofinput contains N, the number of test cases. Each test case begins with aninteger 4 <= M <= 20, the number of sticks. M integers follow; each givesthe 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

 

 

题意描述:给定 一系列数,判断这些数能不能构成一个正方形

解题思路:首先求出正方形边长,然后依次遍历这些数,将这些数中某些数之和等于边长的数去掉,再次遍历,遍历四次即可判断。

程序为:

#include<iostream>

#include<algorithm>

using namespace std;

 

#define maxM 20 //MÌ?Á?䨮¦Ì

 

struct Node

{

    int key;//??º?¨?Ì?¦Ì

    bool visit;//??º?¤?访¤?¨ºy

};

Node node[maxM+1];

 

 

bool square(int i,int cur,int count,int ave);

 

int main()

{

    int N;

    cin>>N;

    while(N>0)

    {

        int M;

        cin>>M;

        node[0].key=M;

        intsum=0;//Á¨¹¨ª

        intavg=0;//?¨´ºy

        boolflag=false;//¨¦|®?¤?Ì?À¨ºº?

        for(int i=1;i<M+1;i++)

        {

            cin>>node[i].key;

            node[i].visit=false;

            sum+=node[i].key;

        }

        if(sum%4!=0)

        {

            flag=false;

        }

        else

        {

            avg=sum/4;

            flag=square(1,0,0,avg);

        }

        if(flag)

            cout<<"yes"<<endl;

        else

            cout<<"no"<<endl;

        N-=1;

    }

    return 0;

}

 

bool square(int i,int cur,int count,int ave)

{

    if(cur==ave)

    {

        count+=1;

        if(count==4)

            returntrue;

        i=1;

        cur=0;

    }

    for(int j=i;j<=node[0].key;j++)

    {

        if(!node[j].visit)

        {

            node[j].visit=true;

            if(((cur+node[j].key)<=ave)&&square(j+1,cur+node[j].key,count,ave))

                returntrue;

            node[j].visit=false;

        }

    }

    return false;

}

回溯法的关键在于写递归函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值