hdu1518 Square(dfs)

Square

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 5987    Accepted Submission(s): 1916

Problem 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
 
深搜,注意优化,就可以了
题意是:给你M根木棍,看看能不能拼出正方形来;
#include<iostream>
#include<cstring>
using namespace std;
int visit[25][2];
int len,sum,m,count,num,k,flag;
void dfs(int now,int len,int index)//now:第几条边  len:该边现在组成的长度 index:用来优化时间
{
    if (now==5)
    {
        flag=1;
        return ;
    }
    if (len==num)
    {
        dfs(now+1,0,0);
        if (flag)//优化时间
            return ;
    }

    for (int i=index;i<m;i++)//从index开始优化时间
    {
        if (!visit[i][1]&&visit[i][0]+len<=num)
        {
            visit[i][1]=1;
            dfs(now,visit[i][0]+len,i+1);//“visit[i][0]+len”不可提出来,
            if (flag)//优化时间
                return;
            visit[i][1]=0;
        }
    }
}    

int main()
{
    int n,i,j;
    scanf("%d",&n);
    while(n--)
    {
        sum=0;
        count=0;
        scanf("%d",&m);
        for(i=0;i<m;i++)
        {
            scanf("%d",&visit[i][0]);
            sum+=visit[i][0];
            visit[i][1]=0;
        }
        if(sum%4!=0||m<4||m>20)
        {
            printf("no\n");
            continue;
        }
        else
        {
            k=m/4;
            num=sum/4;
            for(i=0;i<m;i++)
                if(visit[i][0]>num)
                    {printf("no\n");break;}
            flag = 0;
            dfs(1,0,0);
            if(flag)
                printf("yes\n");
            else
                printf("no\n");
           }

    }
    return 0;
}

/*
5
8 3 4 5 6 7 8 5 2
7 4 5 6 8 10 5 2
7 4 5 6 8 10 4 3
6 3 4 4 3 1 1 
20 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
*/

就这样吧,我会更加努力的

posted @ 2013-08-12 10:07  寻找&星空の孩子  阅读(220)  评论(0编辑  收藏  举报