标签:树形dp 个数 main tchar nod while pen 二分 arch
(学长推荐的,说是好欺负的题)
首先,答案\(k\)具有单调性, \(k\)越大, 正确的可能性越大,所以考虑二分\(k\).
然后,用树形DP进行检查。
\(f[i]\)表示在\(i\)的子树中(不包括\(i\)),染色\(k\)个后还需要的染色次数。
\(son[i]\)表示\(i\)点儿子的个数,\(sum\)表示\(f[i\) 的子节点 \(]\) 的和。
\(f[i] = max(0, sum + son[i] - k)\)
对于每次二分\(k\)值,进行一次DP,如果\(f[1] <= 0\),说明答案可行。
#include <cstdio>
#include <iostream>
#define orz cout << "AK IOI" <<"\n"
using namespace std;
const int maxn = 3e5 + 10;
inline int read()
{
int x = 0, f = 1;
char ch = getchar();
while (ch < ‘0‘ || ch > ‘9‘) {if(ch == ‘-‘) f = -1; ch = getchar();}
while (ch >= ‘0‘ && ch <= ‘9‘) {x = (x << 3) + (x << 1) + (ch ^ 48);ch = getchar();}
return x * f;
}
int n;
struct node{
int u, v, nxt;
}e[maxn << 1];
int js, head[maxn];
void add(int u, int v)
{
e[++js] = (node){u, v, head[u]};
head[u] = js;
}
int son[maxn], f[maxn];
void dfs(int u, int fa)
{
for(int i = head[u]; i; i = e[i].nxt)
{
int v = e[i].v;
if(v == fa) continue;
son[u]++;
dfs(v, u);
}
}
void dfs2(int u, int fa, int mid)
{
f[u] = son[u] - mid;
for(int i = head[u]; i; i = e[i].nxt)
{
int v = e[i].v;
if(v == fa) continue;
dfs2(v, u, mid);
if(f[v] > 0) f[u] += f[v];
}
}
int main()
{
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
n = read();
for(int i = 1; i < n; i++)
{
int u = read(), v = read();
add(u, v), add(v, u);
}
dfs(1, 0);
int l = son[1], r = 0, ans;
for(int i = 1; i <= n; i++) r = max(r, son[i]);
while(l <= r)
{
int mid = (l + r) >> 1;
dfs2(1, 0, mid);
if(f[1] <= 0) ans = mid, r = mid - 1;
else l = mid + 1;
}
printf("%d", ans);
return 0;
}
标签:树形dp 个数 main tchar nod while pen 二分 arch
原文地址:https://www.cnblogs.com/yangchengcheng/p/14728783.html