• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
magicat
博客园    首页    新随笔    联系   管理    订阅  订阅
E. Gardener and Tree 拓扑排序板子

E. Gardener and Tree

将度为1的顶点加入队列,做拓扑排序,记录点的遍历层次,答案为 n-前k层的点的数量

 

//  AC one more times

void solve()
{

    int n;  cin>>n;
    int k;  cin>>k;
    int st[n+10];memset(st,0,sizeof st);
    vector<int> son[n+10];
    int d[n+10];memset(d,0,sizeof d);
    for(int i=1;i<=n+3;i++)
        son[i].clear();
    
    for(int i=1;i<=n-1;i++)
    {
        int u,v;    cin>>u>>v;
        son[u].pb(v);
        son[v].pb(u);
        d[u]++,d[v]++;
    }
    queue<int> q;
    for(int i=1;i<=n;i++)
    {
        if(d[i]==1)
            q.push(i),st[i]=1;
    }

    while(!q.empty())
    {
        int t=q.front();    q.pop();
        for(auto &it:son[t])
        {
            int j=it;
            if(--d[j]==1)
            {
                st[j]=st[t]+1;
                q.push(j);
            }
        }
    }   
    int ans=0;
    for(int i=1;i<=n;i++)
        if(st[i]<=k)   ans++;
    cout<<n-ans<<endl;

    return;
}    
   
int main()
{
    std::ios::sync_with_stdio(false);   cin.tie(nullptr), cout.tie(nullptr);
    
    int T;cin>>T;while(T--)
        solve();    


    return 0;
}

 

 

本文来自博客园,作者:magicat,转载请注明原文链接:https://www.cnblogs.com/magicat/p/16535716.html

posted on 2022-07-30 20:03  magicat  阅读(32)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3