Codeforces 1566E Buds Re-hanging

12 篇文章 0 订阅
2 篇文章 0 订阅

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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值