[2020牛客暑期多校训练营第二场] C题 Cover the Tree

Cover the Tree

题意:

给一棵含有n结点的树,要求补充链(也可以理解为边),使得链覆盖所有的边。
(这里提一下什么叫链覆盖边?由于题目已说n个结点(n-1)条边组成的树,那么想想我们在添加链时,必定形成环,而这个“覆盖边”我认为就是:每一条边在添加链后都在形成的环里)

题解:

这题很容易想到,添加最少数量的链并且让每条边都在添加链后形成的环里,那么链必定是连接叶子结点,但问题来了,链的数量和如何连接怎么办?

用一棵树举例(这里引用用户ccsu_gcr的图)
A
很容易看到,单纯的将叶子结点4、5和6、7连接,是不符合要求的,因为添加的链没有覆盖1-2边和1-3边,但如果4、6和5、7连接,就是符合要求的。很容易猜想出链的个数为(leafnum+1)/2。
那么如何将叶子结点连接呢?首先必须按照dfs序进行排列,(这里有很多代码没有按照dfs序,而是按照编号大小排序水过,很明显是不正确的,将上图6和5的结点互换位置,你看4、6和5、7连接符合要求吗?),连接的方法按相邻两两互连不正确,但可以按照叶子结点一半跨越连接,每次取出叶子结点 i 和( i+leafnum/2)即可。

代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
 
const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=1e5+10;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N=2e5+10;
 
vector<int> g[N];
vector<int> leaf;
int book[N];
int num=0;
void dfs(int u)
{
    if(g[u].size()==1)
    {
        num++;
        leaf.push_back(u);
    }
    for(int i=0;i<g[u].size();i++)
    {
        int v=g[u][i];
        if(!book[v])
        {
            book[v]=1;
            dfs(v);
        }
    }
}
int main()
{
    int n;
    cin >> n;
    for(int i=1;i<n;i++)
    {
        int u,v;
        cin >> u >> v;
        g[u].pb(v);
        g[v].pb(u);
    }
    book[1]=1;
    dfs(1);
    int ans=0;
    ans=(num+1)/2;
    cout << ans << endl;
    if(leaf.size()>0)
    {
        for(int i=0;i<ans;i++) printf("%d %d\n",leaf[i], leaf[i+(leaf.size()/2)]);
    }
}
//8
//2 5
//5 4
//2 1
//1 3
//3 6
//3 7
//3 8

猜你喜欢

转载自blog.csdn.net/weixin_44235989/article/details/107332926
今日推荐