hdu 4277 USACO ORZ dfs暴力列挙+map

4500 ワード

// N   rails  N rails           
//dfs    +(map)
#include<cstdio>
#include<cstring>
#include<map>
#include<iostream>
using namespace std ;
int ans ;
int a[20] ;
int n ;
int sum  =  0 ;
struct node
{
    int a , b , c ;
    bool operator == (const node d)const
    {return (d.a==a&&d.b==b&&d.c==c);}
};
bool operator < (const node d , const node e){
    if(d.a == e.a)
    {
        if(d.b == e.b)
        return d.c < e.c ;
        return d.b < e.b ;
    }
    return d.a < e.a;}
bool operator == (const node d , const node e){return (d.a==e.a&&d.b==e.b&&d.c==e.c);}
map<node , int> ma ;
void dfs(int sum_1 , int sum_2 , int sum_3 ,int pos)
{
    if(sum_1 > sum/2 || sum_2 > sum/2 || sum_3 > sum/2)
    return ;
    if(pos == n + 1)
    {
        if(sum_1 <= sum_2 && sum_2 <= sum_3)
        if(sum_2 + sum_3 > sum_1 && sum_3)
        {
            struct node  a = {sum_1 , sum_2 , sum_3} ;
            if(ma[a] == 0)
            {
                ans++ ;
                ma[a] = 1;
            }
        }
        return ;
    }
    dfs(sum_1+a[pos] , sum_2 , sum_3 , pos+1) ;
    dfs(sum_1 , sum_2 + a[pos] , sum_3 , pos+ 1) ;
    dfs(sum_1 , sum_2 , sum_3+ a[pos] , pos+1) ;
}
int main()
{
   //freopen("in.txt" ,"r" , stdin) ;
    int T ;
    scanf("%d" ,&T) ;
    while(T--)
    {
        sum =  0 ;
        scanf("%d" ,&n) ;
        for(int i = 1;i <= n;i++)
        scanf("%d" ,&a[i]) ,sum += a[i] ;
        ans = 0 ;ma.clear() ;
        dfs(0 , 0 , 0 ,1) ;
        printf("%d
"
,ans) ; } }