C.Cover the Tree - 2020牛客暑期多校训练营(第二场) (构造,覆盖问题)

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\n",cnt);
    for(int i=0;i<cnt;i++)
        printf("%d %d\n",ans[i],ans[(i+sz/2)%sz]);
    return 0;
}

1590627-20200713210125436-1997932716

posted @ 2020-07-14 08:15  popozyl  阅读(238)  评论(0编辑  收藏  举报