生活随笔
收集整理的这篇文章主要介绍了
牛客多校2 - Cover the Tree(dfs序)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
题目链接:点击查看
题目大意:给出一棵无根树,问能否选择数量最少的链,使得所有的路径都被覆盖到
题目分析:读完题后不难看出,假设叶子结点的个数为 x,那么答案就是 x / 2 向上取整
然后说结论,dfs序依次拿出叶子结点后,第 i 个叶子结点和第 i + x/2 个匹配就可以了,证明如下:
代码:
#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;
}
总结
以上是生活随笔为你收集整理的牛客多校2 - Cover the Tree(dfs序)的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。