搜索,最优性剪枝,记忆化
Code:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=15;
map<ll,int>mp;
int n,a[N],h[N];
inline ll H(int x){
ll res=x-1;
for(int i=1;i<x;i++) res=res*17+h[i];
return res;
}
ll dfs(int x,int y){
if(a[x]>(x-y)*3) return 0;
if(x==y){
if(x==1) return 1;
for(int i=1;i<x;i++) h[i]=a[i];
sort(h+1,h+x);
ll hs=H(x);
return mp.count(hs)?mp[hs]:mp[hs]=dfs(x-1,1);
}
ll ans=0;
if(a[x]>=3){a[x]-=3;ans+=dfs(x,y+1);a[x]+=3;}
if(a[x] && a[y]){a[x]--;a[y]--;ans+=dfs(x,y+1);a[x]++;a[y]++;}
if(a[y]>=3){a[y]-=3;ans+=dfs(x,y+1);a[y]+=3;}
return ans;
}
int main() {
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
cout<<dfs(n,1);
return 0;
}