codeforces round936——C(Tree Cutting)

文章讲述了在给定树结构和剪切点的情况下,如何使用贪心策略和二分查找来求解删除k条边后每个子树的最大长度的问题。关键在于设计dfs函数以检查子树长度并进行贪心切割。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:Tree Cuttingicon-default.png?t=N7T8https://codeforces.com/contest/1946/problem/C

题目大意:给你一个树和一个剪切点树k,你需要求出删除 k 条边后,每个子树的最大长度。

这个题目,很容易就能想到二分子树的长度,难的是check函数,对于二分的长度,我们需要dfs贪心的切割,如果子树长度达到mid就切断,cnt++,最后判断一下cnt是否大于m。

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 2e5 + 10;
const int mod  = 1e9 + 7;
int n,m;
vector<vector<int>> e(N);
int cnt = 0;
int dfs(int now,int lst,int t){//贪心的dfs,now是当前节点,lst是上一个节点,t是子树的最短长度
    int num = 1;     //numk记录子树长度
    for (auto x : e[now]) { //遍历当前节点的子节点
        if(x == lst) continue;
        num += dfs(x,now,t);    //num加上子节点的长度
    }
    if(num >= t){   //当前子树满足条件,就return 0;
        cnt++;
        return 0;
    }
    return num; //否则返回当前子树的长度
}

bool check(int mid){
    cnt = 0;
    dfs(1,-1,mid);
    return cnt > m; //满足就返回false
}

void solve(){
    cin>>n>>m;
    for (int i = 1; i <= n; ++i) {      //清空数组
        e[i].clear();
    }
    for (int i = 1; i < n; ++i) {
        int u,v;
        cin>>u>>v;
        e[u].push_back(v);
        e[v].push_back(u);
    }
    int l = 1,r = n;
    while (l < r){      //本题容易看出使用二分,主要是check不容易写出来
        int mid = (l + r + 1) >> 1;
        if(check(mid)) l = mid;
        else{
            r = mid - 1;
        }
    }
    cout<<r<<endl;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t = 1;
    cin>>t;
    while(t--){
        solve();
    }
    return 0 ;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值