E. Tests for problem D------思维(难)

We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.

Given an undirected labeled tree consisting of n vertices, find a set of segments such that:

both endpoints of each segment are integers from 1 to 2n, and each integer from 1 to 2n should appear as an endpoint of exactly one segment;
all segments are non-degenerate;
for each pair (i,j) such that i≠j, i∈[1,n] and j∈[1,n], the vertices i and j are connected with an edge if and only if the segments i and j intersect, but neither segment i is fully contained in segment j, nor segment j is fully contained in segment i.
Can you solve this problem too?

Input
The first line contains one integer n (1≤n≤5⋅105) — the number of vertices in the tree.

Then n−1 lines follow, each containing two integers xi and yi (1≤xi,yi≤n, xi≠yi) denoting the endpoints of the i-th edge.

It is guaranteed that the given graph is a tree.

Output
Print n pairs of integers, the i-th pair should contain two integers li and ri (1≤li<ri≤2n) — the endpoints of the i-th segment. All 2n integers you print should be unique.

It is guaranteed that the answer always exists.

Examples
inputCopy

6
1 2
1 3
3 4
3 5
2 6
outputCopy
9 12
7 10
3 11
1 5
2 4
6 8
inputCopy
1
outputCopy
1 2

题意:给你一棵树,让你生成一堆线段,线段相交表示连边。线段包含不行。

解析:
在这里插入图片描述
假设这边有一棵树
那么线段的情况如下
在这里插入图片描述
我们可以分析出对于左端点应该从后往前cnt++,然后再到右端点从前往后cnt++,这样一定可以构成。

这边有更详细的视频讲解:
https://www.bilibili.com/video/av80058531?p=5



#include<bits/stdc++.h>
using namespace std;
const int N=1e6+1000;
vector<int> G[N];
int t,x,y,l[N],r[N],cnt;
void dfs(int x,int fa)
{
	for(int i=G[x].size()-1;i>=0;i--)
	{
		int v=G[x][i];
		if(v==fa) continue;
		l[v]=cnt++;
	}
	r[x]=cnt++;
	for(int i=0;i<G[x].size();i++)
	{
		int v=G[x][i];
		if(v==fa) continue;
		dfs(v,x);
	}
}
int main()
{
	scanf("%d",&t); 
	for(int i=0;i<t-1;i++)
	{
		scanf("%d %d",&x,&y);
		G[x].push_back(y);
		G[y].push_back(x);
	}
	cnt=1;
	l[1]=cnt++;
	dfs(1,-1);
	for(int i=1;i<=t;i++) printf("%d %d\n",l[i],r[i]);
 } 


发布了309 篇原创文章 · 获赞 6 · 访问量 5251

猜你喜欢

转载自blog.csdn.net/qq_43690454/article/details/104084142