Codeforces 581F Zublicanes and Mumocrates 树形dp

时间:2022-04-11 11:10:45

Zublicanes and Mumocrates

dp[ i ][ j ][ k ] 表示 以 i 为根的子树, 占领 i 的 是 j 并且第一个人占了 i 子树的 k 个叶子节点的最小值。

然后随便d 1 d 就好了。

#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, leaf;
int dp[N][][N];
int tmp[][N];
int sum[N];
bool isleaf[N];
vector<int> G[N]; void dfs(int u, int fa) {
if(isleaf[u]) {
dp[u][][] = dp[u][][] = ;
sum[u] = ;
return;
}
dp[u][][] = dp[u][][] = ;
for(auto& v : G[u]) {
if(v == fa) continue;
dfs(v, u);
memset(tmp, inf, sizeof(tmp));
for(int i = ; i < ; i++) {
for(int j = ; j < ; j++) {
for(int c1 = ; c1 <= sum[u]; c1++) {
for(int c2 = ; c2 <= sum[v]; c2++) {
chkmin(tmp[i][c1 + c2], dp[u][i][c1] + dp[v][j][c2] + (i != j));
}
}
}
}
sum[u] += sum[v];
memcpy(dp[u], tmp, sizeof(dp[u]));
}
} int main() {
memset(dp, inf, sizeof(dp));
scanf("%d", &n);
for(int i = ; i < n; i++) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
if(n == ) return puts(""), ;
int root = -;
for(int i = ; i <= n; i++) {
if(SZ(G[i]) != ) root = i;
else leaf++, isleaf[i] = true;
}
dfs(root, );
printf("%d\n", min(dp[root][][leaf >> ], dp[root][][leaf >> ]));
return ;
} /*
*/