Treeland consists of $n$ cities and $n-1$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.

There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.

The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $k$ and the number of companies taking part in the privatization is minimal.

Choose the number of companies $r$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $k$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $r$ that there is such assignment to companies from $1$ to $r$ that the number of cities which are not good doesn't exceed $k$. [Image] The picture illustrates the first example ($n=6, k=2$). The answer contains $r=2$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $3$) is not good. The number of such vertices (just one) doesn't exceed $k=2$. It is impossible to have at most $k=2$ not good cities in case of one company. 


-----Input-----

The first line contains two integers $n$ and $k$ ($2 \le n \le 200000, 0 \le k \le n - 1$) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.

The following $n-1$ lines contain roads, one road per line. Each line contains a pair of integers $x_i$, $y_i$ ($1 \le x_i, y_i \le n$), where $x_i$, $y_i$ are cities connected with the $i$-th road.


-----Output-----

In the first line print the required $r$ ($1 \le r \le n - 1$). In the second line print $n-1$ numbers $c_1, c_2, \dots, c_{n-1}$ ($1 \le c_i \le r$), where $c_i$ is the company to own the $i$-th road. If there are multiple answers, print any of them.


-----Examples-----
Input
6 2
1 4
4 3
3 5
3 6
5 2

Output
2
1 2 1 1 2 
Input
4 2
3 1
1 4
1 2

Output
1
1 1 1 
Input
10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9

Output
3
1 1 2 3 2 3 1 3 1

Difficulty: HARD
Tags: Graph algorithms

Graph traversal

Constructive algorithms

Sorting

Greedy algorithms

Tree algorithms
Skill types: Sorting

Greedy algorithms

Starter code:

Solutions:
(n, k) = map(int, input().split(' '))
deg = [0] * n
neighbors = [[] for i in range(n)]
edges = []
for i in range(n - 1):
	(a, b) = map(int, input().split(' '))
	neighbors[a - 1].append(b - 1)
	neighbors[b - 1].append(a - 1)
	deg[a - 1] += 1
	deg[b - 1] += 1
	edges.append((a - 1, b - 1))
deg = list(sorted(deg))
r = deg[-(k + 1)]
print(r)
from collections import deque
colors = {}
q = deque()
q.append((None, 0))
while q:
	(par, node) = q.popleft()
	parcolor = None if par is None else colors[par, node]
	color = 0 if parcolor != 0 else 1
	deg = len(neighbors[node])
	for neigh in neighbors[node]:
		if neigh != par:
			if deg > r:
				colors[node, neigh] = 0 if parcolor is None else parcolor
			else:
				colors[node, neigh] = color
				color += 1
				if color == parcolor:
					color += 1
			q.append((node, neigh))
for (a, b) in edges:
	if (a, b) in colors:
		print(colors[a, b] + 1, end=' ')
	else:
		print(colors[b, a] + 1, end=' ')


def set_color(edge, colors, color):
	colors[edge] = color
	colors[edge[1], edge[0]] = color

def set_node_color(node, parent, parent_color, index, bad_nodes, colors):
	color = 1
	for child_node in (child for child in index[node] if child != parent):
		if color == parent_color:
			color += 1
		new_color = parent_color if node in bad_nodes else color
		color += 1
		set_color((node, child_node), colors, new_color)
		set_node_color(child_node, node, new_color, index, bad_nodes, colors)

def solve(n, k, edges):
	colors = {edge: None for edge in edges}
	index = {i: set() for i in range(1, n + 1)}
	for (a, b) in edges:
		index[a].add(b)
		index[b].add(a)
	nodes = sorted(list(range(1, n + 1)), key=lambda x: len(index[x]), reverse=True)
	bad_nodes = set(nodes[:k])
	frontier = [(nodes[k], None, None)]
	while frontier:
		(next_, parent_node, parent_color) = frontier.pop()
		color = 1
		for child_node in (ele for ele in index[next_] if ele != parent_node):
			if color == parent_color:
				color += 1
			new_color = parent_color if next_ in bad_nodes else color
			set_color((next_, child_node), colors, new_color)
			color += 1
			frontier.append((child_node, next_, new_color))
	return [colors[edge] for edge in edges]

def main():
	(n, k) = map(int, input().split())
	edges = []
	for i in range(n - 1):
		edges.append(tuple(map(int, input().split())))
	result = solve(n, k, edges)
	print(len(set(result)))
	print(' '.join(map(str, result)))
main()


def strelizia():
	oh_pie = 0
	kaguya = 0
	owe_pie = [(0, 0, 0)]
	while kaguya <= oh_pie:
		o_pie = oh_pie
		while kaguya <= o_pie:
			x = owe_pie[kaguya][0]
			p = owe_pie[kaguya][1]
			c = 1
			l = len(stamen[x])
			if l > virm:
				for (to, ed) in stamen[x]:
					if to != p:
						darling[ed - 1] = c
						owe_pie.append((to, x, c))
						oh_pie += 1
			else:
				for (to, ed) in stamen[x]:
					if c == owe_pie[kaguya][2]:
						c += 1
					if to != p:
						darling[ed - 1] = c
						owe_pie.append((to, x, c))
						oh_pie += 1
						c += 1
			kaguya += 1
darling = []
franxx = input().split()
pistil = []
stamen = []
for i in range(0, int(franxx[0])):
	pistil.append(0)
	stamen.append([])
for i in range(1, int(franxx[0])):
	darling.append(0)
	edge = input().split()
	stamen[int(edge[0]) - 1].append((int(edge[1]) - 1, i))
	stamen[int(edge[1]) - 1].append((int(edge[0]) - 1, i))
	pistil[int(edge[0]) - 1] += 1
	pistil[int(edge[1]) - 1] += 1
pistil.sort()
virm = pistil[int(franxx[0]) - int(franxx[1]) - 1]
print(virm)
strelizia()
for i in range(1, int(franxx[0])):
	print(darling[i - 1], end=' ')


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
R = [list(map(int, input().split())) for i in range(n - 1)]
RDICT = {tuple(sorted([R[i][0], R[i][1]])): i for i in range(n - 1)}
C = [[] for i in range(n + 1)]
for (x, y) in R:
	C[x].append(y)
	C[y].append(x)
CLEN = []
for i in range(1, n + 1):
	CLEN.append(len(C[i]))
from collections import Counter
counter = Counter(CLEN)
CV = sorted(counter.keys(), reverse=True)
cvsum = 0
cities = 1
for cv in CV:
	cvsum += counter[cv]
	if cvsum > k:
		cities = cv
		break
print(cities)
ANS = [0] * (n - 1)
from collections import deque
QUE = deque()
QUE.append([1, 1])
VISITED = [0] * (n + 1)
while QUE:
	(city, roadnum) = QUE.pop()
	VISITED[city] = 1
	for to in C[city]:
		if VISITED[to] == 0:
			ANS[RDICT[tuple(sorted([city, to]))]] = roadnum
			roadnum = roadnum % cities + 1
			QUE.append([to, roadnum])
print(*ANS)


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq
import math, string

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	(N, K) = getInts()
	graph = dd(set)
	count = [0] * N
	edges = []
	for n in range(N - 1):
		(A, B) = getInts()
		A -= 1
		B -= 1
		graph[A].add(B)
		graph[B].add(A)
		count[A] += 1
		count[B] += 1
		edges.append((min(A, B), max(A, B)))
	count2 = []
	for (i, a) in enumerate(count):
		count2.append((a, i))
	count2.sort(key=lambda x: x[0])
	ans = count2[N - K - 1][0]
	edge_D = dd(int)
	visited = set()

	@bootstrap
	def dfs(node, col):
		visited.add(node)
		for neighbour in graph[node]:
			if neighbour not in visited:
				col += 1
				col %= ans
				edge_D[min(node, neighbour), max(node, neighbour)] = col + 1
				yield dfs(neighbour, col)
		yield
	print(ans)
	dfs(1, -1)
	ans = [edge_D[A, B] for (A, B) in edges]
	print(*ans)
	return
solve()


from __future__ import print_function
import os, sys, atexit
if sys.version_info[0] < 3:
	range = xrange
	from cStringIO import StringIO as BytesIO
	sys.stdout = BytesIO()
else:
	from io import BytesIO
	sys.stdout = BytesIO()
	_write = sys.stdout.write
	sys.stdout.write = lambda s: _write(s.encode())
atexit.register(lambda : os.write(1, sys.stdout.getvalue()))
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = [int(x) for x in input().split()]
coupl = [[] for _ in range(n)]
edge_ind = [[] for _ in range(n)]
for _ in range(n - 1):
	(u, v) = [int(x) - 1 for x in input().split()]
	coupl[u].append(v)
	coupl[v].append(u)
	edge_ind[u].append(_)
	edge_ind[v].append(_)
leaf = min(range(n), key=lambda i: len(coupl[i]))
order = [leaf]
stack = [leaf]
found = [False] * n
found[leaf] = True
while stack:
	node = stack.pop()
	for nei in coupl[node]:
		if not found[nei]:
			found[nei] = True
			order.append(nei)
			stack.append(nei)
degs = sorted(range(n), key=lambda i: len(coupl[i]), reverse=True)
free = [False] * n
for i in degs[:k]:
	free[i] = True
colors_needed = len(coupl[degs[k]])
colors_used = [set() for _ in range(n)]
edge_color = [0] * (n - 1)
for node in order:
	next_color = 1
	if not free[node]:
		while next_color in colors_used[node]:
			next_color += 1
	for i in range(len(coupl[node])):
		edge_i = edge_ind[node][i]
		nei = coupl[node][i]
		if edge_color[edge_i] == 0:
			edge_color[edge_i] = next_color
			colors_used[node].add(next_color)
			colors_used[nei].add(next_color)
			if not free[node]:
				next_color += 1
				while next_color in colors_used[node]:
					next_color += 1
print(colors_needed)
print(*edge_color)


from collections import deque
import sys
input = sys.stdin.readline

def bfs(s):
	queue = deque([s])
	cv = [0] * n
	cv[s] = 1
	par = [-1] * n
	while queue:
		u = queue.popleft()
		col = 1 + int(par[u] == 1)
		for nxt in adj[u]:
			if not cv[nxt]:
				if u in bad:
					if (u, nxt) in d_edges:
						d_edges[u, nxt] = 1
					else:
						d_edges[nxt, u] = 1
					par[nxt] = 1
				else:
					if (u, nxt) in d_edges:
						d_edges[u, nxt] = col
					else:
						d_edges[nxt, u] = col
					par[nxt] = col
					col += 1
					if col == par[u]:
						col += 1
				queue.append(nxt)
				cv[nxt] = 1
(n, k) = [int(item) for item in input().split()]
adj = {}
edges = []
for i in range(n - 1):
	(u, v) = [int(item) - 1 for item in input().split()]
	edges.append((u, v))
	for j in range(2):
		if u in adj:
			adj[u].append(v)
		else:
			adj[u] = [v]
		(u, v) = (v, u)
d_edges = {edge: 0 for edge in edges}
p = sorted([(i, len(adj[i])) for i in range(n)], key=lambda p: (p[1], p[0]), reverse=True)
r = p[k][1]
print(r)
bad = set((p[i][0] for i in range(k)))
bfs(0)
print(*[d_edges[edge] for edge in edges])


import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import defaultdict
from itertools import islice

def solve():
	(n, k) = map(int, input().split())
	G = [list() for _ in range(n)]
	E = []
	ans = defaultdict(lambda : 1)
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		(u, v) = (u - 1, v - 1)
		G[u].append(v)
		G[v].append(u)
		E.append((u, v))
	V = list(range(n))
	V.sort(key=lambda v: -len(G[v]))
	r = len(G[V[k]])
	visited = [False] * n
	stack = []
	for u in islice(V, k, None):
		if not visited[u]:
			stack.append((u, 0))
			while stack:
				(u, skip) = stack.pop()
				visited[u] = True
				e = 0
				for v in G[u]:
					if not visited[v]:
						e += 1
						if e == skip:
							e += 1
						ans[u, v] = e
						if len(G[v]) <= r:
							stack.append((v, e))
	print(r)
	out = []
	for (u, v) in E:
		if (u, v) not in ans:
			(u, v) = (v, u)
		out.append(str(ans[u, v]))
	print(' '.join(out))
solve()


import sys
zz = 1
sys.setrecursionlimit(10 ** 5)
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def ii():
	return input().rstrip()

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def gtc(tc, ans):
	print('Case #' + str(tc) + ':', ans)

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j, n, m):
	return 0 <= i < n and 0 <= j < m

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = 1
uu = t

def dfs(i, p=-1, c=-1):
	st = [(i, p, c)]
	vis = {}
	while st:
		(i, p, c) = st[-1]
		if i in vis:
			st.pop()
			continue
		vis[i] = 1
		r = (c + 1) % ans
		for j in a[i]:
			if j != p:
				col[edge[i, j]] = r + 1
				st.append((j, i, r))
				r = (r + 1) % ans
while t > 0:
	t -= 1
	d = {}
	(n, k) = mi()
	col = [0] * (n - 1)
	d = [0] * (n + 1)
	a = [[] for i in range(n + 1)]
	edge = {}
	for i in range(n - 1):
		(x, y) = mi()
		d[x] += 1
		d[y] += 1
		edge[x, y] = i
		edge[y, x] = i
		a[x].append(y)
		a[y].append(x)
	p = {}
	for i in range(1, n + 1):
		inc(p, d[i])
	r = []
	for i in p:
		r.append([i, p[i]])
	r.sort(reverse=True)
	ans = 1
	for i in range(len(r)):
		if k < r[i][1]:
			ans = r[i][0]
			break
		k -= r[i][1]
	print(ans)
	dfs(1)
	print(*col)


import sys
input = sys.stdin.buffer.readline
from collections import deque

def dfs():
	visited = [0 for i in range(n + 1)]
	queue = deque()
	queue.append([1, 0])
	add = 0
	while queue:
		par = queue.popleft()
		if visited[par[0]] == 1:
			continue
		visited[par[0]] = 1
		add = (marked[par[1]] + 1) % fix
		for child in graph[par[0]]:
			if visited[child[0]] == 0:
				marked[child[1]] = add
				add = (add + 1) % fix
				queue.append([child[0], child[1]])
(n, k) = map(int, input().split())
graph = [[] for i in range(n + 1)]
counted = [0 for i in range(n + 1)]
for i in range(n - 1):
	(a, b) = map(int, input().split())
	counted[a] += 1
	counted[b] += 1
	graph[a].append([b, i])
	graph[b].append([a, i])
arr = []
for i in range(1, n + 1):
	arr.append(counted[i])
arr.sort(reverse=True)
fix = arr[k]
marked = [0 for i in range(n + 1)]
marked[0] = -1
dfs()
print(max(marked) + 1)
for i in range(n - 1):
	print(marked[i] + 1, end=' ')
print()


import sys
from collections import deque

def norm_edge(i, j):
	return (i, j) if i < j else (j, i)
inpt = sys.stdin.read().split('\n')
(n, k) = list(map(int, inpt[0].split()))
edges = []
for edge_str in inpt[1:n]:
	(i, j) = tuple([int(x) - 1 for x in edge_str.split()])
	edges.append(norm_edge(i, j))
degree = [0 for _ in range(n)]
neigh = [[] for _ in range(n)]
for (i, j) in edges:
	degree[i] += 1
	degree[j] += 1
	neigh[i].append(j)
	neigh[j].append(i)
r = sorted(degree)[-(k + 1)]
print(r)
visited = set()
color = {}
q = deque([0])
visited = set([0])
while len(q) > 0:
	i = q.popleft()
	used_color = None
	for j in neigh[i]:
		if j not in visited:
			visited.add(j)
			q.append(j)
		e = norm_edge(i, j)
		if used_color is None and e in color:
			used_color = color[e]
	next_color = 0
	for j in neigh[i]:
		e = norm_edge(i, j)
		if e in color:
			continue
		if next_color == used_color:
			next_color += 1
		color[e] = next_color % r if next_color >= r else next_color
		next_color += 1
print(' '.join([str(color[e] + 1) for e in edges]))


from collections import defaultdict
from math import log2
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.setrecursionlimit(10 ** 5)

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(u, p, curr):
	global l
	cnt = 1
	for j in adj[u]:
		if j != p:
			rem = (curr + cnt) % l
			if rem == 0:
				rem = l
			edge[d[u, j]] = rem
			yield dfs(j, u, rem)
			cnt += 1
	yield
(n, k) = map(int, input().split())
adj = [[] for i in range(n + 1)]
tot = [0 for i in range(n + 1)]
d = dict()
for j in range(n - 1):
	(u, v) = map(int, input().split())
	adj[u].append(v)
	adj[v].append(u)
	tot[u] += 1
	tot[v] += 1
	d[u, v] = j
	d[v, u] = j
tot = tot[1:]
tot.sort()
l = 1
r = n - 1
while l < r:
	m = (l + r) // 2
	if n - bisect_left(tot, m + 1) > k:
		l = m + 1
	else:
		r = m
cnt = [0 for i in range(n + 1)]
edge = [-1 for i in range(n - 1)]
dfs(1, 0, 0)
print(l)
print(*edge)