我们可以先求出每个子树最多能放多少台装罐机()。考虑设 为子树 能容纳多少装罐机, 为节点 是否能放装罐机, 为子树 的大小。预先 dfs 一遍,如果 ,则表示子树放完他们自己的装罐机、配套的发电机()以后,至少还能留一个空位放发电机,给位于 的装罐机供电。这时就可以设 ,。
然后,从上往下把所需要的装罐机()和发电机()往下摊派。设当前子树接到的任务是放 个装罐机,再向上面提供 点电力。为了尽量把装罐机往上放,在 dfs 到的每个子树中,优先处理上面给的装罐机任务。如果上面没有装罐机任务、或者当前节点不能放装罐机,则处理发电机任务。
一个节点如果不能处理完所有任务的话,还需要把任务再向下摊派。先摊派装罐机任务,则对于儿子 ,需要摊派 台装罐机。由于儿子 放下 台装罐机后还需要放 台发电机,所以能往子树 中摊派的发电机数量就只有 。把任务发到儿子之和,记得给 和 减少对应的数量。
时间复杂度:
code
#include <bits/stdc++.h>
#define _eggy_ using
#define _party_ namespace
_eggy_ _party_ std; _party_ llamn{ _party_{
numeric_limits<int> INT;
numeric_limits<long long> LL;
int n,m,i,j,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19,t20,t21,t22,t23,t24,t25,t26,t27,t28,t29,t30;
vector<int> e[1000100];
int c[1000100], sz[1000100], ans[1000100];
bool can[1000100];
void dfs(int d, int f)
{
if (f) e[d].erase(find(e[d].begin(),e[d].end(),f));
sz[d] = 1; for (int i : e[d])
dfs(i,d), sz[d] += sz[i], c[d] += c[i];
if (c[d] * 2 < sz[d]-1) c[d] += (can[d] = 1);
}void down(int d, int f1, int f2)
{
if (f1 && can[d]) f1 -= can[d], f2 += (ans[d] = 1); // 放装罐机
else if (f2) ans[d] = 2, f2--; // 放发电机
for (int i : e[d])
{
if ((!f2) && (!f1)) break;
int i1 = min(f1,c[i]);
down(i,i1,min(f2,sz[i] - 2*i1));
f1 -= i1, f2 -= min(f2,sz[i] - 2*i1);
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> k; for (i = 1; i < n; i++)
{
cin >> t1 >> t2;
e[t1].push_back(t2);
e[t2].push_back(t1);
}dfs(1,0);
if (c[1] < k) return cout << "No", 0;
else cout << "Yes\n"; down(1,k,0);
for (i = 1; i <= n; i++) cout << ans[i] << ' ';
return 0;
}
}}signed main(){return llamn::main();}