Solution -「JLOI 2015」「洛谷 P3262」战争调度
\(\mathcal{Description}\)
Link.
给定一棵 \(n\) 层的完全二叉树,你把每个结点染成黑色或白色,满足黑色叶子个数不超过 \(m\)。对于一个叶子 \(u\),若其 \(k\) 级父亲与其同为黑色,则对答案贡献 \(a_{uk}\);若同为白色,则对答案贡献 \(b_{uk}\)。求最大贡献和。
\(n\le10\)。
\(\mathcal{Solution}\)
想要 DP,比如令 \(f(u,i)\) 表示 \(u\) 子树内有 \(i\) 个叶子为黑色时的最大贡献和。但发现这根本没法转移 qwq。
那……爆搜呢?
从上往下搜索,直接钦定当前非叶结点是黑是白,搜到叶子时,在向上计算当前叶子是黑色/白色时的贡献,回溯时简单背包。复杂度 \(\mathcal O(n4^n)\),可过欸!
\(\mathcal{Code}\)
/* Clearink */
#include <cstdio>
const int MAXN = 10;
int n, m, a[1 << MAXN | 5][MAXN + 5], b[1 << MAXN | 5][MAXN + 5];
int f[1 << MAXN | 5][1 << MAXN | 5];
bool fight[1 << MAXN | 5];
inline void chkmax ( int& a, const int b ) { a < b && ( a = b, 0 ); }
inline void solve ( const int u, const int d ) {
for ( int i = 0; i <= 1 << d; ++ i ) f[u][i] = 0;
if ( !d ) {
for ( int i = 1; i <= n; ++ i ) {
if ( fight[u >> i] ) f[u][1] += a[u][i];
else f[u][0] += b[u][i];
}
} else {
for ( int k = 0; k <= 1; ++ k ) {
fight[u] = k;
solve ( u << 1, d - 1 ), solve ( u << 1 | 1, d - 1 );
for ( int i = 0; i <= 1 << d >> 1; ++ i ) {
for ( int j = 0; j <= 1 << d >> 1; ++ j ) {
chkmax ( f[u][i + j], f[u << 1][i] + f[u << 1 | 1][j] );
}
}
}
}
}
int main () {
scanf ( "%d %d", &n, &m ), -- n;
for ( int i = 0; i < 1 << n; ++ i ) {
for ( int j = 1; j <= n; ++ j ) {
scanf ( "%d", &a[( 1 << n ) + i][j] );
}
}
for ( int i = 0; i < 1 << n; ++ i ) {
for ( int j = 1; j <= n; ++ j ) {
scanf ( "%d", &b[( 1 << n ) + i][j] );
}
}
solve ( 1, n );
int ans = 0;
for ( int i = 0; i <= m; ++ i ) chkmax ( ans, f[1][i] );
printf ( "%d\n", ans );
return 0;
}