poj 2362 Square

Square
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 19541   Accepted: 6797

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
no
yes

題意:給出一組長度數列,讓判斷這M個數能否連成一個正方形

分析:首先是剪枝:sum%4!=0的肯定不滿足條件,另外如果num[i]>sum/4肯定也是           不滿足的。

<span style="font-size:14px;">#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int N,M,flag,num[10010],vist[10010];
int edgs,rest,sum;

void dfs(int x,int add,int edgs)
{
    //cout<<num[x]<<edgs<<add<<" ";
    if(flag==1)
        return ;
    if(edgs==4)//邊數滿足4條即可
    {
        flag = 1;
        return ;
    }
    if(num[x]>sum/4)//剪枝
    {
        flag = 0;
        return ;
    }
    for(int j=x+1;j<=M;j++)
    {
        if(!vist[j]&&add+num[j]<=sum/4)
        {
            if(add+num[j]==sum/4)//滿足構成一條邊的條件
            {
                vist[j] = true ;
                dfs(0,0,edgs+1);
                vist[j] = false ;
            }

            else//不滿足構成一條邊時繼續dfs
            {
                vist[j] = true ;
                dfs(j,add+num[j],edgs);
                vist[j] = false;
            }
        }
    }
}

int main()
{
    scanf("%d",&N);
    while(N--)
    {
        memset(vist,false,sizeof(vist));
        flag =0;
        sum = 0;
        scanf("%d",&M);
        for(int i=1;i<=M;i++)
        {
            scanf("%d",&num[i]);
            sum += num[i];
        }
        if(sum%4 !=0)
            flag=0;
        else {
            dfs(0,0,0);
        }
        if(flag)
            printf("yes\n");
        else printf("no\n");
    }
    return 0;
}</span><span style="font-size: 18pt;">
</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章