2020牛客暑期多校训练营(第二场)C Cover the Tree

题目描述
Given an unrooted tree, you should choose the minimum number of chains that all edges in the tree are covered by at least one chain. Print the minimum number and one solution. If there are multiple solutions, print any of them.

输入描述:
The first line contains one integer n~(1\leq n \leq 2\times10^5)n (1≤n≤2×10
5 ), denoting the size of the tree.Following {n-1}n−1 lines each contains two integers u,v~(1\leq u < v \leq n)u,v (1≤u It’s guaranteed that the given graph forms a tree.

输出描述:
The first line contains one integer {k}k, denoting the minimum number of chains to cover all edges.
Following {k}k lines each contains two integers u,v~(1\leq u,v \leq n)u,v (1≤u,v≤n), denoting a chain you have chosen. Here {u = v}u=v is permitted, which covers no edge.

示例1
输入
复制
5
1 2
1 3
2 4
2 5
输出
复制
2
2 3
4 5
说明
2020牛客暑期多校训练营(第二场)C Cover the Tree_第1张图片

void DFS(int x,int fx) {
    if(du[x]==1) {
        a[++ans]=x;
        return;
    }
    for(int i=0; i<vec[x].size(); i++) {
        int now=vec[x][i];
        if(now==fx) continue;
        DFS(now,x);
    }
}
int main() {
    scanf("%d",&k);
    for(int i=1; i<k; i++) {
        scanf("%d%d",&u,&v);
        du[u]++;
        du[v]++;
        if(du[u]>=2&&flag) root=u,flag=0;
        if(du[v]>=2&&flag) root=v,flag=0;
        vec[u].push_back(v);
        vec[v].push_back(u);
    }
    if(root==-1) {
        printf("1\n%d %d",u,v);
        return 0;
    }
    DFS(root,-1e9);
    printf("%d\n",(ans+1)/2);
    for(int i=1; i<=ans/2; i++) printf("%d %d\n",a[i],a[(ans+1)/2+i]);
    if(ans&1) printf("%d %d\n",root,a[ans/2+1]);
    return 0;
}

你可能感兴趣的:(2020牛客暑期多校训练营(第二场)C Cover the Tree)