zoukankan      html  css  js  c++  java
  • C.Cover the Tree

    C.Cover the Tree 题解

    题目链接 https://ac.nowcoder.com/acm/contest/5667/C

    当做结论记下来好了。用最少条链来覆盖一棵树的时候,最优解为 s / 2 上取整.

    方法为先找到一个非叶节点(度>=2)作为根(对于无根树),然后dfs找出所有的叶节点加入vector.

    AC代码(网友)

    #include<iostream>
    #include<cstdio>
    #include<string>
    #include<ctime>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #include<stack>
    #include<climits>
    #include<queue>
    #include<map>
    #include<set>
    #include<sstream>
    #include<cassert>
    using namespace std;
      
    typedef long long LL;
      
    typedef unsigned long long ull;
      
    const int inf=0x3f3f3f3f;
      
    const int N=2e5+100;
     
    vector<int>node[N],ans;
     
    void dfs(int u,int fa)
    {
        if(node[u].size()==1)
            ans.push_back(u);
        for(auto v:node[u])
        {
            if(v==fa)
                continue;
            dfs(v,u);
        }
    }
     
    int main()
    {
    #ifndef ONLINE_JUDGE
    //  freopen("input.txt","r",stdin);
    //  freopen("output.txt","w",stdout);
    #endif
    //  ios::sync_with_stdio(false);
        int n;
        scanf("%d",&n);
        for(int i=1;i<n;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            node[u].push_back(v);
            node[v].push_back(u);
        }
        int root=1;
        while(node[root].size()==1)
            root++;
        dfs(root,-1);
        int sz=ans.size(),cnt=(sz+1)/2;
        printf("%d
    ",cnt);
        for(int i=0;i<cnt;i++)
            printf("%d %d
    ",ans[i],ans[(i+sz/2)%sz]);
        return 0;
    }
    
    

    1590627-20200713210125436-1997932716

    ---- suffer now and live the rest of your life as a champion ----
  • 相关阅读:
    软件设计中的立足点
    Clojure基础
    团队凝聚力
    执行力与领导力
    工作与生活
    分离焦虑OR责任焦虑
    保持激情
    立足点
    论研发管理--开篇
    初级码农常犯错误
  • 原文地址:https://www.cnblogs.com/popodynasty/p/13297086.html
Copyright © 2011-2022 走看看