Cover the Tree

Posted cadcadcad

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cover the Tree相关的知识,希望对你有一定的参考价值。

Cover the Tree

技术图片

就当作是一个结论吧…当要用链覆盖所有的边时,对叶子节点根据dfs序排序后,根据((i,i+s/2))的配对规则进行配对即可,如果有奇数个叶子节点,则将其与根节点相连。

// Created by CAD on 2020/7/13.
#include <bits/stdc++.h>

#define fi first
#define se second
#define pii pair<int,int>
#define ll long long
using namespace std;

const int maxn=2e5+5;
vector<int> g[maxn];
int cnt=0;
vector<pii> leaf;
void dfs(int x,int f){
    if(g[x].size()==1) leaf.push_back({++cnt,x});
    for(auto i:g[x])
        if(i==f) continue;
        else dfs(i,x);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;cin>>n;
    for(int i=1;i<=n-1;++i){
        int a,b;cin>>a>>b;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    int root=1;
    for(int i=1;i<=n;++i)
        if(g[i].size()>1){
            root=i;
            break;
        }
    dfs(root,0);
    vector<pii> ans;
    int leafsiz=leaf.size();
    if(leafsiz%2)
        leaf.push_back({++cnt,root}),leafsiz++;
    for(int i=0;i<leafsiz/2;++i)
        ans.push_back({leaf[i].se,leaf[i+leafsiz/2].se});

    cout<<ans.size()<<endl;
    for(auto i:ans)
        cout<<i.fi<<" "<<i.se<<endl;

    return 0;
}

以上是关于Cover the Tree的主要内容,如果未能解决你的问题,请参考以下文章

环境初始化 Build and Install the Apache Thrift IDL Compiler Install the Platform Development Tools(代码片段

maven web项目的web.xml报错The markup in the document following the root element must be well-formed.(代码片段

What's the difference between @Component, @Repository & @Service annotations in Spring?(代码片段

RuntimeError: An attempt has been made to start a new process before the current process has...(代码片段

detectron2报AttributeError: Attribute ‘evaluator_type‘ does not exist in the metadata of dataset(代码片段

Nginx——Nginx启动报错Job for nginx.service failed because the control process exited with error code(代码片段