poj2362

来源:互联网 发布:电脑无法登陆淘宝网 编辑:程序博客网 时间:2024/05/22 13:21
                                                           Square


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


我觉得这是一道练习dfs+剪枝的好题,也算是入门题。

题意:从n根木棍中组合成一个正方形,每一根都要选。

<span style="font-size:18px;">#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int a[25],len,visited[25];//len表示平均长度int n,t;int dfs(int num,int s,int lenth)//num表示已经形成了得边或者正在形成的边,s表示从后往前搜索的起点,length表示正在形成的边的长度{    if(num==3)//已经形成了3边,其余的一边就肯定已经满足了        return 1;    for(int i=s;i>=0;i--)//从s往前搜索,将a[i]的长度添加到正在形成的边上面    {        if(!visited[i])//如果该点没有被添加        {            visited[i]=1;            if(lenth+a[i]<len){//添加后长度小于len,则num不变,将a[i]添加到边上去,从i-1这根木棍继续往前搜                if(dfs(num,i-1,lenth+a[i]))                    return 1;            }            else if(lenth+a[i]==len){//添加后长度等于len,则num+1,重新从末尾开始搜,并将这条新的边的长度设为0                if(dfs(num+1,n-1,0))                    return 1;            }            visited[i]=0;        }    }    return 0;}int main(){    scanf("%d",&t);    while(t--)    {        int sum=0;        memset(visited,0,sizeof(visited));        scanf("%d",&n);        for(int i=0;i<n;sum+=a[i],i++)            scanf("%d",&a[i]);        sort(a,a+n);        len=sum/4;        if(sum%4!=0||len<a[n-1]||n<4)//不能被4整除,最大的长度大于平均长度,数目小于4都是不能组成正方形的        {            printf("no\n");            continue;        }        if(dfs(0,n-1,0))            printf("yes\n");        else            printf("no\n");    }    return 0;}</span>


0 0