题目链接:点击查看
题目大意:给出一棵树,现在要求从点1出发遍历所有的结点一遍后再回到点1,额外给出一个时光机,可以到某个节点的任意时刻,需要满足的条件如下:
- 初始时在节点 1 ,时间为 0
- 每次操作分为下列两种:
- ( v , t ) -> ( v , t_pre ) ,满足 0 <= t_pre < t (利用时光机)
- ( v , t ) -> ( v_next , t + 1 ) ,满足 v 和 v_next 之间存在一条连边 (正常行走)
- 所有的 ( v , t ) 必须各不相同
- 所有的节点必须至少被遍历一遍
在上述条件下,若要使得所有 t 中的最大值最小,输出一种构造方案
题目分析:其实不难看出,最终所有 t 中的最大值,和每个点的度数有关系,所以我们可以求出这个最大值为 mmax ,也就是最大的时间点,接下来需要想出一种构造方案,使得既能满足利用时光机时不能冲突,也要满足正常行走的条件,这里直接给出构造方法吧
首先对于任意一个节点 u 来说,先求出他的所有子节点有多少个,记为 son ,不难看出,节点 u 至少需要经过 son + 1 次才行,一次是从节点 u 的父节点下来,剩下 son 次是从子节点上来,同时可以知道, 0 <= son < mmax ,当节点为叶子结点时,son 显然为 0 ,当节点为度数最大的那个节点时,son = mmax - 1 (减去父节点)
到此为止,我们先考虑满足每个操作的第二种情况,也就是正常行走的情况,这种情况必须要求从节点 u 到达节点 v 时,时间之差必须为一,如果我们先不考虑最大值 mmax 的限制的话,设从父节点到节点 u 的时间点为 t 的话,我们可以让节点 u 到子节点的时间分别为 t + 1 , t + 2 , t + 3 .... 以此类推,如何保证呢?只需要根据相对关系实现下面两点即可:(设 t_u 为进入到节点 u 时的时间,t_v 为进入到子节点 v 时的时间)
- 从节点 u 进入到子节点时的时间为 t_u + 1
- 从子节点返回到到节点 u 时的时间为 t_v - 1
仔细思考一下,会发现确实很巧妙
那么剩下的就是解决有 mmax 限制的那个时光机的条件了,因为每个节点的每个时间点至多只能出现一次,而每个节点最多就会使用 son + 2 次时间点:
- 一次是从父节点下来时的 t
- son 次是从子节点上来时的 t + 1 , t + 2 ...等等
- 一次是从最大值转到最小值时使用的(多使用了一次时光机)
所以我们可以将每个结点使用的区间固定在 [ mmax - son - 1 , mmax ] 之间,换句话说,就是让节点 u 到子节点的时间分别为 t + 1 , t + 2 , t + 3 .... ( mmax - son - 1 ) +1 , ( mmax - son - 1 ) + 2 .... t - 1 ,也就是当 t 到达 mmax 时,让其变为最小值 mmax - son - 1 然后继续加一就行了
注意特判一下节点 1
利用 dfs 实现起来非常简单,终点是需要理解构造的巧妙
代码:
#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<unordered_map>
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];
vector<pair<int,int>>ans;
int mmax;
void dfs(int u,int fa,int t)//在区间 [ mmax - son - 1 , mmax ] 内赋值
{
int temp=t;
ans.push_back(make_pair(u,t));
int son=node[u].size()-(u!=1);//有多少个子节点
for(auto v:node[u])
{
if(v==fa)
continue;
if(t==mmax)//如果已经到最大值了,那么切换成最小值
{
t=mmax-son-1;
ans.push_back(make_pair(u,t));
}
t++;
dfs(v,u,t);
ans.push_back(make_pair(u,t));
}
if(u!=1&&t!=temp-1)
ans.push_back(make_pair(u,temp-1));
}
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);
}
for(int i=1;i<=n;i++)
mmax=max(mmax,(int)node[i].size());
dfs(1,-1,0);
printf("%d\n",ans.size());
for(int i=0;i<ans.size();i++)
printf("%d %d\n",ans[i].first,ans[i].second);
return 0;
}