首页 > 代码库 > HJDU 1518—— Square(DFS)

HJDU 1518—— Square(DFS)

简单深搜~~~~

<strong>#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<functional>
#define M 30
using namespace std;
int vis[M],a[M],n,flag,sum;
void dfs(int s,int cur,int d)
{
    if(cur==3||flag){
        flag=1;
        return ;
    }
    for(int i=s;i<n;++i){

        if(vis[i]||(d+a[i]>sum)) continue ;
        vis[i]=1;
        if(d+a[i]==sum) dfs(0,cur+1,0);
        else dfs(i+1,cur,d+a[i]);
        if(flag) return ;
        vis[i]=0;
        if(d==0) break; //超强力剪枝  瞬间时间变为46MS
        while(a[i]==a[i+1]) i++; //剪枝

    }
    return ;
}
int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int t;
    scanf("%d",&t);
    while(t--){
        cin>>n;
        sum=0;
        for(int i=0;i<n;++i){
            scanf("%d",&a[i]);
            sum+=a[i];
            vis[i]=0;
        }
        if(sum%4){
            printf("no\n");
            continue;
        }
        sum/=4;
        sort(a,a+n,greater<int>());
        if(a[n-1]>sum){
            printf("no\n");
            continue;
        }
        flag=0;
        dfs(0,0,0);
        if(flag) printf("yes\n");
        else printf("no\n");
    }
    return 0;
}</strong>