https://codeforces.com/contest/1646/problem/D
Codeforces Round #774 (Div. 2) D
定义一个点为good为它的权和等于其他相邻的点的和.计算出一个树最多有多少个好点,并且统计出该条件最少的权和.
思路:观察后发现只有两个点,一条边的情况下才有可能有两个good的点相邻,否则他们总是不相邻的.问题转化为求这个树的最大独立集.用
d
p
(
u
,
b
)
dp(u,b)
dp(u,b)表示u是否在集合中,b=0,代表不是,b=1代表是.
如果u在集合中,那么v一定不在.反之,u不在集合中,v可以再可以不在,两者取max即可.
最后,根据树形dp的思想,用树型结果在把结果还原即可.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
const int INF = 1e9+7;
typedef pair<int,int> pii;
vector<int> G[maxn];
pii dp[maxn][2];// first = num of good , second = sum of node
pii dfs(int u,int b,int fa){
pii & res = dp[u][b];
if(res.first>=0) return res;
res = {b,b ? (-G[u].size()):-1};
for(auto v : G[u]){
if(v==fa) continue;
pii next = dfs(v,0,u);
if(b==0) next = max(next,dfs(v,1,u));
res.first += next.first;
res.second += next.second;
}
return res;
}
vector<bool> good;
void build(pii val,int u,int fa){
if(val==dfs(u,0,fa)){
good[u] = false;
for(auto v : G[u]){
if(v==fa) continue;
build(max(dfs(v,0,u),dfs(v,1,u)),v,u);
}
}
else {
good[u] = true;
for(auto v : G[u]){
if(v==fa) continue;
build(dfs(v,0,u),v,u);
}
}
}
int main(){
// freopen("1.txt","r",stdin);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;cin>>n;
for(int i=0;i<=n;i++){
dp[i][0] = dp[i][1] = {-1,-1};
}
good.resize(n+1);
for(int i=1;i<=n-1;i++){
int u,v;
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
if(n==2){
cout<<"2 2\n1 1\n";
return 0;
}
pii val = max(dfs(1,0,0),dfs(1,1,0));
cout<<val.first<<" "<<-val.second<<"\n";
build(val,1,0);
for(int i=1;i<=n;i++){
if(good[i]) cout<<G[i].size()<<" ";
else cout<<1<<" ";
}
}