Codeforces 279D The Minimum Number of Variables 状压dp

时间:2023-03-09 17:34:20
Codeforces 279D The Minimum Number of Variables 状压dp

The Minimum Number of Variables

我们定义dp[ i ][ mask ]表示是否存在 处理完前 i 个a, b中存者 a存在的状态是mask 的情况。

然后用sosdp处理出,状态为state的a, 能组成的数字, 然后转移就好啦。

#include<bits/stdc++.h>
#define LL long long
#define LD long double
#define ull unsigned long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ALL(x) (x).begin(), (x).end()
#define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = + ;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + ;
const double eps = 1e-;
const double PI = acos(-); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;}
template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < ) a += mod;}
template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;}
template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} int n;
int a[N]; int cnt[ << ];
int sos[ << ];
bool dp[][ << ]; int main() {
scanf("%d", &n);
for(int i = ; i < ( << n); i++)
cnt[i] = cnt[i - (i & - i)] + ;
for(int i = ; i < n; i++) scanf("%d", &a[i]);
for(int i = ; i < n; i++) {
for(int j = i; j < n; j++) {
int ret = a[i] + a[j];
for(int k = ; k < n; k++) {
if(ret == a[k])
sos[( << i) | ( << j)] |= << k;
}
}
}
for(int i = ; i < n; i++)
for(int mask = ; mask < ( << n); mask++)
if(mask >> i & ) sos[mask] |= sos[mask ^ ( << i)]; dp[][] = ;
for(int i = ; i < n - ; i++) {
for(int mask = ; mask < ( << n); mask++) {
if(!dp[i][mask]) continue;
if(sos[mask] >> (i + ) & ) {
dp[i + ][mask | ( << (i + ))] = true;
for(int j = ; j <= i; j++) {
if(mask >> j & ) {
dp[i + ][(mask ^ ( << j)) | ( << (i + ))] = true;
}
}
}
}
}
int ans = inf;
for(int i = ; i < ( << n); i++)
if(dp[n - ][i]) chkmin(ans, cnt[i]);
if(ans == inf) ans = -;
printf("%d\n", ans);
return ;
} /*
*/