Codeforces 1325C. Ehab and Path-etic MEXs(构造)

Description

You are given a tree consisting of n nodes. You want to write some labels on the tree’s edges such that the following conditions hold:

Every label is an integer between 0 and n−2 inclusive.
All the written labels are distinct.
The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn’t written on any edge on the unique simple path from node u to node v.

Input

The first line contains the integer n (2≤n≤105) — the number of nodes in the tree.

Each of the next n−1 lines contains two space-separated integers u and v (1≤u,v≤n) that mean there’s an edge between nodes u and v. It’s guaranteed that the given graph is a tree.

Output

Output n−1 integers. The ith of them will be the number written on the ith edge (in the input order).

Examples
input

3
1 2
1 3

output

0
1

input

6
1 2
1 3
2 4
2 5
5 6

output

0
3
2
4
1

题目大意

给出一颗树,需要你对每一条边编号,保证对于所有点对MEX(u,v)的最大值最小
MEX(u,v)表示从节点u到节点v的唯一简单路径上的任何边上都没有写入的最小非负整数。

思路

只要保证0,1,2不在同一路径上(如果可能),那最大值就是2
找到一个点如果从这个点开始有超过3条边,那这三个数就可以填在这三条边上,再随意填剩下的数

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
vector<pair<int,int> > w[maxn];
int vis[maxn];
int main(){
    int n,a,b;
	scanf("%d",&n);
	for(int i=1;i<n;++i){
		scanf("%d %d",&a,&b);
		w[a].push_back(make_pair(b,i));
		w[b].push_back(make_pair(a,i));
	}
	int now=0;
	memset(vis,-1,sizeof(vis));
	for(int i=1;i<=n;++i){
		if(w[i].size()>2){
			vis[w[i][0].second]=now++;
			vis[w[i][1].second]=now++;
			vis[w[i][2].second]=now++;
			break;
		}
	}
	for(int i=1;i<n;++i){
		if(vis[i]==-1)vis[i]=now++;
	}
	for(int i=1;i<n;++i){
		printf("%d%c",vis[i],i==n?'\n':' ');
	}
    return 0;
}
发布了157 篇原创文章 · 获赞 56 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43984169/article/details/105606206