首页 > 代码库 > HDU 1518 Square

HDU 1518 Square


dfs+剪枝!
AC代码如下:
///dfs+剪枝  62MS 300K

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;

int n,m;
int a[50];
int vis[50];

bool cmp(int a,int b)
{
    return a>b;
}

int dfs(int v,int cur,int bg)
{
    if(cur==4)
        return 1;
    int i;
    for(i=bg;i<n;i++)
    {
        int flag=0;
        if(!vis[i]&&a[i]+v==m)
        {
            flag=1;
            vis[i]=1;
            if(dfs(0,cur+1,0))
                return 1;
            vis[i]=0;
            return 0;
        }
        if(!vis[i]&&a[i]+v<m)
        {
            flag=1;
            vis[i]=1;
            if(dfs(a[i]+v,cur,i+1))
                return 1;
            vis[i]=0;
            if(v==0)
                return 0;
        }
        while(flag&&i+1<n&&a[i+1]==a[i])
            i++;
    }
    return 0;
}

int main()
{
    int t;
    int i;
    scanf("%d",&t);
    while(t--)
    {
        int sum=0;
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        sort(a,a+n,cmp);
        if(sum%4!=0||a[0]>sum/4)
        {
            printf("no\n");
            continue;
        }
        m=sum/4;
        memset(vis,0,sizeof vis);
        if(dfs(0,0,0))
            printf("yes\n");
        else printf("no\n");

    }
    return 0;
}