Codeforces 1566E Buds Re-hanging
(rating :2000)
链接
http://codeforces.com/problemset/problem/1566/E
题意
给一棵树,根节点为1,定义一种叫 Bud(芽)的东西 ------ 该节点不是根节点,有孩子且孩子全都是树叶(leaf)。每次操作可以将芽重新连接到树上的任意位置,要求最小化树叶的数量,直接输出结果。
input
5
7
1 2
1 3
1 4
2 5
2 6
4 7
6
1 2
1 3
2 4
2 5
3 6
2
1 2
7
7 3
1 5
1 3
4 6
4 7
2 1
6
2 1
2 3
4 5
3 4
3 6
output
2
2
1
2
1
改变前:
改变后:
思路
由于可以将Bud重新放到任意位置,我们直接将所有Bud都先连到根节点上,这样保证所有的节点深度不超过3.(根节点深度为1)
观察发现,把一个Bud连在另一个Bud下面可以使叶子-1。
于是,我们可以将所有的Bud都移到一个Bud上,这样,叶子的个数就会减少(Bud-1)个。
至于这最后一个Bud,我们观察根节点1是否有直接连着leaf,如果有的话,把它连接到任意一个leaf上,结果再-1.
因此 , 当根节点不连接 leaf 时 , ans = leaf - (Bud - 1) = n - Bud * 2 。
否则 ans = leaf - Bud = n - Bud * 2 - 1 。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 4e5+100;
struct E{
int to;
int nxt;
}e[N<<2];
int head[N],tot;
void add_edge(int u,int v){
e[++tot].to = v;
e[tot].nxt = head[u];
head[u] = tot;
}
int bud,leaf;
bool vis[N];
void dfs(int u,int f){
bool is_leaf = true;
int cnt = 0;
for(int i=head[u];i;i=e[i].nxt){
int v = e[i].to;
if(v==f) continue;
dfs(v,u);
if(!vis[v]) is_leaf = false,cnt++;
}
if(!is_leaf&&u!=1){
//cout<<u<<endl;
bud++;
leaf+=cnt;
vis[u] = true;
}
}
int n;
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
cin>>n;
tot = 0,bud = 0,leaf = 0;
for(int i=1;i<=n;i++) vis[i] = false,head[i] = 0;
for(int i=1;i<n;i++){
int x,y;
cin>>x>>y;
add_edge(x,y);
add_edge(y,x);
}
dfs(1,0);
bool flg = false;
for(int i=head[1];i;i=e[i].nxt){
int v = e[i].to;
if(!vis[v]) flg = true;
}
//cout<<"bud"<<bud<<endl;
if(!flg){
cout<<(n-bud*2)<<endl;
}
else{
cout<<(n-bud*2-1)<<endl;
}
}
}