回溯法Square

来源:互联网 发布:高级美工培训 编辑:程序博客网 时间:2024/06/16 22:27

 

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