「CF815C」Karen and Supermarket
传送门
Luogu
解题思路
树形背包。
设 \(f[i][j][0/1]\) 表示在以 \(i\) 为根的子树中选 \(j\) 件商品的最少花费。
边界条件:
\(f[i][j][0] = \min\limits_{0\le k\le siz[son]}\left\{f[i][j - k][0]+f[son][k][0]\right\}\)
\(f[i][j][1] = \min\limits_{0\le k\le siz[son]}\left\{f[i][j - k][1]+f[son][k][0]\right\}\)
\(f[i][j][1] = \min\limits_{0\le k\le siz[son]}\left\{f[i][j - k][1]+f[son][k][1]\right\}\)
最后输出最大的满足 \(\min\left\{f[1][i][0],f[1][i][1]\right\}\le b\) 的 \(i\) 即可。
细节注意事项
- 咕咕咕
参考代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <ctime>
#include <vector>
#define rg register
using namespace std;
template < typename T > inline void read(T& s) {
s = 0; int f = 0; char c = getchar();
while (!isdigit(c)) f |= (c == '-'), c = getchar();
while (isdigit(c)) s = s * 10 + (c ^ 48), c = getchar();
s = f ? -s : s;
}
const int _ = 1000010;
const int __ = 2000010;
int tot, head[_], nxt[__], ver[__];
inline void Add_edge(int u, int v)
{ nxt[++tot] = head[u], head[u] = tot, ver[tot] = v; }
int n, k, dgr[_], res;
inline int dfs(int u, int f) {
if (dgr[u] == 1) return 0;
vector < int > t;
for (rg int i = head[u]; i; i = nxt[i])
if (ver[i] != f) t.push_back(dfs(ver[i], u) + 1);
sort(t.begin(), t.end());
int len = t.size() - 1;
for (; len > 0; --len)
if (t[len] + t[len - 1] <= k) break; else ++res;
return t[len];
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.in", "r", stdin);
#endif
read(n), read(k);
for (rg int u, v, i = 1; i < n; ++i)
read(u), read(v), Add_edge(u, v), Add_edge(v, u), ++dgr[u], ++dgr[v];
int rt = 1;
for (rg int i = 1; i <= n; ++i)
if (dgr[i] > 1) { rt = i; break; }
dfs(rt, 0);
printf("%d\n", res + 1);
return 0;
}
完结撒花 \(qwq\)