CSU-ACM2017暑期训练4-dfs H- Square HDU

来源:互联网 发布:虚拟币系统源码 编辑:程序博客网 时间:2024/05/17 06:02

题目:

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
34 1 1 1 15 10 20 30 40 508 1 7 2 6 4 4 3 5
Sample Output
yesnoyes


题意 : 给你一堆木棍的长,问你能否把他们连起来成为一个正方形,注意木棍不能折断。也就是问能否把一堆数字通过相加得到4个相同的数字

        思路:显然正方形的边长等于木棍长度总和除4,所以如果不整除或者木棍数量小于四或者最长的木棍比算出来的正方形边长小直接判定不可以。否则的话就根据这个求出来的边长对数列进行搜索,这个搜索没啥剪枝的,直接暴力就可以了,保存一下哪些木棍使用了就成。具体见代码。


代码:

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<string>#include<vector>#include<stack>#include<bitset>#include<cstdlib>#include<cmath>#include<set>#include<list>#include<deque>#include<map>#include<queue>using namespace std;typedef long long ll;const double PI = acos(-1.0);const double eps = 1e-6;const int INF = 1000000000;const int maxn = 100;int T,n,m;int flag,sum,len;int sti[22];int vis[22];void dfs(int l,int step,int pos){    if(flag)        return;    if(step==4)    {        flag=1;    }    for(int i=pos;i<m;i++)    {        if(!flag&&vis[i]==0)        {            vis[i]=1;            if(sti[i]+l==len)            {                dfs(0,step+1,0);                vis[i]=0;            }            else if(sti[i]+l<len)            {                dfs(l+sti[i],step,i+1);                vis[i]=0;            }            vis[i]=0;        }    }}int main(){    scanf("%d",&T);while(T--)    {        scanf("%d",&m);        memset(vis,0,sizeof(vis));        sum=0;        for(int i=0;i<m;i++)        {            scanf("%d",&sti[i]);            sum+=sti[i];        }        sort(sti,sti+m);        len=sum/4;        flag=0;        if(sum%4||m<4||sti[m-1]>len)            printf("no\n");        else        {            dfs(0,0,0);            if(flag)                printf("yes\n");            else                printf("no\n");        }    }    return 0;}