Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.

[Image] 

There are $n$ cities and $n-1$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $1$ to $n$, and the city $1$ is the capital of the kingdom. So, the kingdom has a tree structure.

As the queen, Linova plans to choose exactly $k$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.

A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).

Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.

In order to be a queen loved by people, Linova wants to choose $k$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?


-----Input-----

The first line contains two integers $n$ and $k$ ($2\le n\le 2 \cdot 10^5$, $1\le k< n$)  — the number of cities and industry cities respectively.

Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is a road connecting city $u$ and city $v$.

It is guaranteed that from any city, you can reach any other city by the roads.


-----Output-----

Print the only line containing a single integer  — the maximum possible sum of happinesses of all envoys.


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

Output
7
Input
4 1
1 2
1 3
2 4

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

Output
9


-----Note-----

[Image]

In the first example, Linova can choose cities $2$, $5$, $6$, $7$ to develop industry, then the happiness of the envoy from city $2$ is $1$, the happiness of envoys from cities $5$, $6$, $7$ is $2$. The sum of happinesses is $7$, and it can be proved to be the maximum one.

[Image]

In the second example, choosing cities $3$, $4$ developing industry can reach a sum of $3$, but remember that Linova plans to choose exactly $k$ cities developing industry, then the maximum sum is $2$.

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Graph traversal

Sorting

Greedy algorithms

Tree algorithms

Dynamic programming


Solutions:
from collections import defaultdict
import sys, threading
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
buffer = []

def dfs(graph, n, p, level):
	penalty = 1
	for c in graph[n]:
		if c == p:
			continue
		penalty += dfs(graph, c, n, level + 1)
	buffer.append(level - penalty)
	return penalty

def main():
	(n, k) = map(int, input().split())
	graph = defaultdict(list)
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		graph[a].append(b)
		graph[b].append(a)
	try:
		dfs(graph, 1, None, 1)
	except Exception as e:
		print(e)
	print(sum(sorted(buffer, reverse=True)[:k]))
t = threading.Thread(target=main)
t.start()
t.join()


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def MI1():
	return map(int1, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():

	def dfs():
		first = [True] * n
		stack = [(0, -1)]
		while stack:
			(u, pu) = stack.pop()
			if first[u]:
				first[u] = False
				stack.append((u, pu))
				for v in to[u]:
					if v == pu:
						continue
					dep[v] = dep[u] + 1
					stack.append((v, u))
			else:
				for v in to[u]:
					if v == pu:
						continue
					chi[u] += chi[v] + 1
	(n, k) = MI()
	to = [[] for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = MI1()
		to[u].append(v)
		to[v].append(u)
	dep = [0] * n
	chi = [0] * n
	dfs()
	vv = [dep[u] - chi[u] for u in range(n)]
	vv.sort(reverse=True)
	ans = sum(vv[:k])
	print(ans)
main()


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest
INF = 999999999999999999999999

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	for _ in range(tc):
		(n, k) = ria()
		graph = [[] for i in range(n + 1)]
		for i in range(n - 1):
			(a, b) = ria()
			graph[a].append(b)
			graph[b].append(a)
		dist = [0] * (n + 1)
		dp = [0] * (n + 1)

		def dfs():
			visited = [False] * (n + 1)
			start = 1
			finished = [False] * (n + 1)
			stack = [start]
			while stack:
				start = stack[-1]
				if not visited[start]:
					visited[start] = True
					for child in graph[start]:
						if not visited[child]:
							dist[child] = 1 + dist[start]
							stack.append(child)
				else:
					stack.pop()
					dp[start] += 1
					for child in graph[start]:
						if finished[child]:
							dp[start] += dp[child]
					finished[start] = True
		dfs()
		contribution = []
		for i in range(1, n + 1):
			contribution.append([dist[i] - dp[i], i])
		contribution = sorted(contribution)
		industries = {}
		for i in range(k):
			industries[contribution.pop()[1]] = 1

		def bfs2():
			visited = [False] * (n + 1)
			q = deque([1])
			visited[1] = True
			ans = 0
			while q:
				parent = q.popleft()
				for child in graph[parent]:
					if not visited[child]:
						visited[child] = True
						if child not in industries:
							q.append(child)
						else:
							ans += dist[child] * dp[child]
			wi(ans)
		bfs2()
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


from heapq import heapify, heappush, heappop
input = __import__('sys').stdin.readline
(n, k) = map(int, input().split())
e = [[] for i in range(n + 1)]
xe = [0 for i in range(n + 1)]
deg = [0 for i in range(n + 1)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	e[u].append(v)
	e[v].append(u)
	deg[u] += 1
	xe[u] ^= v
	deg[v] += 1
	xe[v] ^= u
c = [0 for i in range(n + 1)]
d = [0 for i in range(n + 1)]
seen = set()
q = [(1, 0)]
while len(q):
	(u, p) = q.pop()
	if u not in seen:
		q.append((u, p))
	for v in e[u]:
		if v != p:
			if u not in seen:
				d[v] = d[u] + 1
				q.append((v, u))
			else:
				c[u] += c[v]
	if u in seen:
		c[u] += 1
	seen.add(u)
leaves = []
for i in range(2, n + 1):
	if deg[i] == 1:
		leaves.append((-d[i], i))
heapify(leaves)
sol = 0
while k > 0:
	(x, u) = heappop(leaves)
	sol += -x
	k -= 1
	v = xe[u]
	xe[v] ^= u
	deg[u] -= 1
	deg[v] -= 1
	if deg[v] == 1:
		x2 = d[v] - (c[v] - 1)
		heappush(leaves, (-x2, v))
print(sol)


import sys
import threading
sys.setrecursionlimit(2 * 10 ** 5)

def dfs(node, depth, visited, graph, happiness):
	visited[node] = True
	impact = 0
	for child_node in graph[node]:
		if not visited[child_node]:
			impact += 1 + dfs(child_node, depth + 1, visited, graph, happiness)
	happiness.append(depth - impact)
	return impact

def solve():
	(n, k) = map(int, input().split())
	visited = [False] * n
	happiness = []
	graph = {}
	for i in range(n):
		graph[i] = []
	while n != 1:
		(node_1, node_2) = map(int, input().split())
		node_1 -= 1
		node_2 -= 1
		graph[node_1].append(node_2)
		graph[node_2].append(node_1)
		n -= 1
	dfs(0, 0, visited, graph, happiness)
	happiness.sort(reverse=True)
	ans = 0
	for i in range(0, k, 1):
		ans += happiness[i]
	print(ans)
sys.setrecursionlimit(2 ** 32 // 2 - 1)
threading.stack_size(1 << 27)
thread = threading.Thread(target=solve)
thread.start()
thread.join()


import sys, threading
sys.setrecursionlimit(2 * 10 ** 5)

def dfs(index, d, visited, p, dep, ans):
	visited[index] = True
	dep[index] = d
	for i in range(len(ans[index])):
		if visited[ans[index][i]] == False:
			dfs(ans[index][i], d + 1, visited, p, dep, ans)
			p[index] += p[ans[index][i]]

def solve():
	n = list(map(int, input().split()))
	ans = [[] for i in range(n[0])]
	for i in range(n[0] - 1):
		v = list(map(int, input().split()))
		ans[v[0] - 1].append(v[1] - 1)
		ans[v[1] - 1].append(v[0] - 1)
	p = [1 for i in range(n[0])]
	dep = [0 for i in range(n[0])]
	visited = [False for i in range(n[0])]
	dfs(0, 0, visited, p, dep, ans)
	dp = [0 for i in range(n[0])]
	for i in range(n[0]):
		dp[i] = dep[i] - p[i] + 1
	dp.sort(reverse=True)
	sum1 = 0
	for i in range(n[1]):
		sum1 += dp[i]
	print(sum1)

def main():
	solve()
sys.setrecursionlimit(2 ** 32 // 2 - 1)
threading.stack_size(1 << 27)
thread = threading.Thread(target=main)
thread.start()
thread.join()


from collections import deque
import heapq
(n, k) = map(int, input().split())
neigh = [[] for i in range(n)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	neigh[u - 1].append(v - 1)
	neigh[v - 1].append(u - 1)
visited = [0 for i in range(n)]
queue = deque()
queue.append([0, 1])
visited[0] = 1
depth = [1] * n
subtree = [0] * n
seq = [0]
while queue:
	[index, d] = queue.popleft()
	for ele in neigh[index]:
		if visited[ele] == 1:
			continue
		visited[ele] = 1
		seq.append(ele)
		depth[ele] = d + 1
		queue.append([ele, d + 1])
heap = []
ans = 0
seq = seq[::-1]
for index in seq:
	subtree[index] = 1
	for ele in neigh[index]:
		subtree[index] += subtree[ele]
	heapq.heappush(heap, depth[index] - subtree[index])
	ans += depth[index] - subtree[index]
	if len(heap) > k:
		ans -= heapq.heappop(heap)
print(ans)


def dfs():
	while stack:
		(u, p, depth) = stack.pop()
		if not visited[u]:
			visited[u] = True
			stack.append((u, p, depth))
			for v in adj[u]:
				if v != p:
					stack.append((v, u, depth + 1))
		else:
			for v in adj[u]:
				if v != p:
					count[u] += count[v] + 1
			happiness[u] = depth - count[u]
(node, k) = list(map(int, input().split()))
adj = [[] for _ in range(node)]
visited = [False] * node
stack = [(0, -1, 0)]
for _ in range(node - 1):
	(u, v) = list(map(lambda x: int(x) - 1, input().split()))
	adj[u].append(v)
	adj[v].append(u)
count = [0] * node
happiness = [0] * node
dfs()
happiness.sort(reverse=True)
ans = sum(happiness[:k])
print(ans)


import sys
input = sys.stdin.readline
(N, K) = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
	(a, b) = map(int, input().split())
	graph[a - 1].append(b - 1)
	graph[b - 1].append(a - 1)
Par = [-1] * N
que = []
childs = [0] * N
stack = [0]
Ind = [0] * N
D = [0] * N
while stack:
	p = stack[-1]
	if Ind[p] == len(graph[p]):
		stack.pop()
		if stack:
			par = stack[-1]
			Par[p] = par
			childs[par] += childs[p] + 1
	elif len(stack) > 1 and stack[-2] == graph[p][Ind[p]]:
		Ind[p] += 1
	else:
		np = graph[p][Ind[p]]
		D[np] = D[p] + 1
		Ind[p] += 1
		stack.append(np)
B = []
for n in range(N):
	B.append(D[n] - childs[n])
B.sort(reverse=True)
print(sum(B[:K]))


from collections import defaultdict, deque
import os

def get_neighbors(edges):
	neighbors = defaultdict(set, {})
	for (v1, v2) in edges:
		if v1 != v2:
			neighbors[v1].add(v2)
			neighbors[v2].add(v1)
	return dict(neighbors)

def solve(edges, n, k):
	if k == 0:
		return 0
	adj = get_neighbors(edges)
	counts = [1] * (n + 1)
	depths = [0] * (n + 1)
	depths[1] = 0
	stack = [(1, 0, 0)]
	while stack:
		(node, parent, depth) = stack[-1]
		if adj[node]:
			n1 = adj[node].pop()
			adj[n1].remove(node)
			stack.append((n1, node, depth + 1))
		else:
			stack.pop()
			counts[parent] += counts[node]
			depths[node] = depth
	return sum(sorted([s - d - 1 for (s, d) in zip(counts, depths)][1:], reverse=True)[:n - k])

def pp(input):
	(n, k) = map(int, input().split())
	edges = [tuple(map(lambda x: x, map(int, input().split(' ')))) for _ in range(n - 1)]
	print(solve(edges, n, k))
if 'paalto' in os.getcwd():
	from string_source import string_source
	pp(string_source('7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7'))
	pp(string_source('4 1\n1 2\n1 3\n2 4'))
	pp(string_source('8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5'))
else:
	pp(input)


(N, K) = map(int, input().split())
graph = [[] for i in range(N + 1)]
for i in range(N - 1):
	(a, b) = map(int, input().split())
	graph[a].append(b)
	graph[b].append(a)
from collections import deque
d = deque()
e = deque()
visited = [False for _ in range(N + 1)]
distance = [-1 for i in range(N + 1)]
distance[1] = 0
par = [-1 for i in range(N + 1)]
visited[1] = True
d.append(1)
while d:
	while d:
		x = d.popleft()
		for node in graph[x]:
			if visited[node] == False:
				visited[node] = True
				distance[node] = distance[x] + 1
				par[node] = x
				e.append(node)
	if e:
		d = e
		e = deque()
node = []
for i in range(1, N + 1):
	node.append((i, distance[i]))
node.sort(key=lambda x: -x[1])
cnt = [1 for i in range(N + 1)]
for some in node:
	(node, dis) = some
	if par[node] > 0:
		cnt[par[node]] += cnt[node]
for i in range(N + 1):
	cnt[i] -= 1
P = []
for i in range(1, N + 1):
	P.append(cnt[i] - distance[i])
P.sort(reverse=True)
print(sum(P[:N - K]))


import sys, threading

def main():
	(n, k) = map(int, input().split())
	adj = [[] for i in range(n)]
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		adj[a - 1].append(b - 1)
		adj[b - 1].append(a - 1)
	res = []

	def dfs(s, e, depth):
		count = 1
		for u in adj[s]:
			if u != e:
				count += dfs(u, s, depth + 1)
		res.append(depth - count)
		return count
	dfs(0, -1, 1)
	print(sum(sorted(res, reverse=True)[:k]))
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


from sys import stdin, stdout
import heapq

def main():
	(n, k) = list(map(int, stdin.readline().split()))
	tree = [[] for _ in range(n + 1)]
	visited = [0] * (n + 1)
	lev = [0] * (n + 1)
	p = [0] * (n + 1)
	minus = [0] * (n + 1)
	for _ in range(n - 1):
		(a, b) = list(map(int, stdin.readline().split()))
		tree[a].append(b)
		tree[b].append(a)
	stack = [1]
	visited[1] = 1
	level = 1
	last = []
	while stack:
		temp = []
		for x in stack:
			last.append(x)
			for y in tree[x]:
				if visited[y] == 0:
					temp.append(y)
					visited[y] = 1
					p[y] = x
					lev[y] = level
		if not temp:
			break
		stack = temp
		level += 1
	last.reverse()
	stack = last
	for x in stack:
		minus[p[x]] += minus[x] + 1
	res = []
	for i in range(1, n + 1):
		res.append(lev[i] - minus[i])
	res.sort(reverse=True)
	stdout.write(str(sum(res[:k])))
main()


import sys
input = sys.stdin.buffer.readline
from collections import deque
sys.setrecursionlimit(10 ** 9)
(n, k) = map(int, input().split())
con = [[] for _ in range(n + 1)]
for _ in range(n - 1):
	(s, t) = map(int, input().split())
	con[s] += (t,)
	con[t] += (s,)
con[0] += (1,)
dist = [-1] * (n + 1)
dist[0] = 0
par = [None] * (n + 1)
q = deque([0])
order = []
while q:
	cur = q.popleft()
	order.append(cur)
	for nxt in con[cur]:
		if dist[nxt] < 0:
			dist[nxt] = dist[cur] + 1
			par[nxt] = cur
			q.append(nxt)
size = [1] * (n + 1)
for i in order[n:0:-1]:
	size[par[i]] += size[i]
ans = sum(sorted((-size[x] + dist[x] for x in range(1, n + 1)))[::-1][:k])
print(ans)


(n, k) = map(int, input().split())
G = [[] for _ in range(n)]
for _ in range(n - 1):
	(u, v) = map(lambda x: int(x) - 1, input().split())
	G[u].append(v)
	G[v].append(u)
order = []
par = [-1] * n
stack = [0]
while stack:
	v = stack.pop()
	order.append(v)
	for c in G[v]:
		if c != par[v]:
			par[c] = v
			stack.append(c)
par_count = [0] * n
chi_count = [0] * n
for v in order:
	p = par[v]
	if p != -1:
		par_count[v] = par_count[p] + 1
for v in order[::-1]:
	p = par[v]
	if p != -1:
		chi_count[p] += chi_count[v] + 1
score = [par_count[i] - chi_count[i] for i in range(n)]
score.sort(reverse=True)
print(sum(score[:k]))


import sys
import threading
threading.stack_size(10 ** 8)
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

def dfs(i, deep):
	sub = 1
	for key in dic[i]:
		if vis[key] == 0:
			vis[key] = 1
			sub += dfs(key, deep + 1)
	diff[i] = deep - sub
	return sub
(n, k) = [int(x) for x in input().split(' ')]
dic = {}
vis = [0] * (n + 1)
vis[0] = vis[1] = 1
diff = [0] * (n + 1)

def main():
	for i in range(n - 1):
		(a, b) = [int(x) for x in input().split(' ')]
		if not a in dic:
			dic[a] = []
		if not b in dic:
			dic[b] = []
		dic[a].append(b)
		dic[b].append(a)
	dfs(1, 1)
	print(sum(sorted(diff[1:], reverse=True)[:k]))
t = threading.Thread(target=main)
t.start()
t.join()


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = list(map(int, input().split()))
graph = {i + 1: [] for i in range(n)}
for i in range(n - 1):
	(u, v) = list(map(int, input().split()))
	graph[u].append(v)
	graph[v].append(u)
node = 1
visited = {i: True for i in graph}
parent = {i: 0 for i in graph}
dist = [0] * n
size = [0] * n
stack = [node]
while stack:
	node = stack.pop()
	if visited[node]:
		visited[node] = False
		for i in graph[node]:
			if visited[i]:
				dist[i - 1] = dist[node - 1] + 1
				parent[i] = node
				stack.append(i)
visited = {i: True for i in graph}
node = 1
stack = [node]
while stack:
	node = stack.pop()
	if visited[node]:
		visited[node] = False
		stack.append(node)
		v = 0
		for i in graph[node]:
			if visited[i]:
				stack.append(i)
				v += 1
		size[node - 1] = v
	elif parent[node] - 1 >= 0:
		size[parent[node] - 1] += size[node - 1]
print(sum(sorted([i - j for (i, j) in zip(size, dist)], reverse=True)[:n - k]))


import sys
import threading
from collections import defaultdict
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
input = sys.stdin.readline
B = []
A = defaultdict(list)

def dfs(now, fa, depth):
	son = 1
	for to in A[now]:
		if to != fa:
			son += dfs(to, now, depth + 1)
	B.append(depth - son)
	return son

def main():
	(n, m) = map(int, input().split())
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		x -= 1
		y -= 1
		A[x].append(y)
		A[y].append(x)
	dfs(0, -1, 1)
	print(sum(sorted(B, reverse=True)[:m]))
t = threading.Thread(target=main)
t.start()
t.join()


import sys
import threading
sys.setrecursionlimit(10 ** 8 + 5)
threading.stack_size(10 ** 8 + 5)

def solve():
	(n, k) = map(int, input().split())
	s = [set() for _ in range(n + 1)]
	d = []
	used = [0] * (n + 1)

	def depth(x, val):
		res = 1
		used[x] = 1
		for v in s[x]:
			if not used[v]:
				res += depth(v, val + 1)
		d.append(res - val)
		return res
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		s[u].add(v)
		s[v].add(u)
	depth(1, 1)
	d.sort(reverse=True)
	res = 0
	for i in range(n - k):
		res += d[i]
	print(res)
threading.Thread(target=solve).start()


from sys import stdin, stdout

def INI():
	return int(stdin.readline())

def INL():
	return [int(_) for _ in stdin.readline().split()]

def INS():
	return stdin.readline()

def MOD():
	return pow(10, 9) + 7

def OPS(ans):
	stdout.write(str(ans) + '\n')

def OPL(ans):
	[stdout.write(str(_) + ' ') for _ in ans]
	stdout.write('\n')
from types import GeneratorType

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 dfsLevel(u, c):
	V[u] = True
	Level[u] = c
	for _ in X[u]:
		if not V[_]:
			yield dfsLevel(_, c + 1)
	yield

@bootstrap
def dfsSubTree(u):
	V[u] = True
	x = 0
	for _ in X[u]:
		if not V[_]:
			yield dfsSubTree(_)
			x += SubTree[_]
	SubTree[u] += 1 + x
	yield
(n, k) = INL()
X = [[] for _ in range(n + 1)]
for _ in range(n - 1):
	(u, v) = INL()
	X[u].append(v)
	X[v].append(u)
V = [False for _ in range(n + 1)]
Level = [0 for _ in range(n + 1)]
dfsLevel(1, 0)
V = [False for _ in range(n + 1)]
SubTree = [0 for _ in range(n + 1)]
dfsSubTree(1)
ANS = []
for _ in range(1, n + 1):
	ANS.append(Level[_] - (SubTree[_] - 1))
ANS.sort(reverse=True)
ans = 0
for _ in range(k):
	ans += ANS[_]
OPS(ans)


import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor, ceil
from heapq import heappop, heappush, heapify
mod = 10 ** 9 + 7

def main():
	for _ in range(1):
		(n, k) = map(int, input().split())
		graph = [[] for i in range(n + 1)]
		for i in range(n - 1):
			(u, v) = map(int, input().split())
			graph[u].append(v)
			graph[v].append(u)
		dist = [-1] * (n + 1)
		parent = [-1] * (n + 1)
		dist[1] = 0
		l = [1]
		parent[1] = 0
		while len(l):
			node = l.pop()
			for adj in graph[node]:
				if adj != parent[node]:
					parent[adj] = node
					dist[adj] = dist[node] + 1
					l.append(adj)
		q = []
		done = [0] * (n + 1)
		for i in range(1, n + 1):
			if len(graph[i]) == 1 and i != 1:
				q.append((-dist[i], i))
		heapify(q)
		ans = 0
		cnt = [0] * (n + 1)
		for i in range(k):
			(rev, node) = heappop(q)
			ans -= rev
			sub = 0
			done[node] += 1
			cnt[parent[node]] += 1
			if len(graph[parent[node]]) - (1 if parent[node] != 1 else 0) == cnt[parent[node]]:
				sub = 0
				for i in graph[parent[node]]:
					sub += done[i]
				done[parent[node]] = sub
				t = -(dist[parent[node]] - sub)
				heappush(q, (t, parent[node]))
		print(ans)
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')
main()


import sys
readline = sys.stdin.readline

class Segtree:

	def __init__(self, A, intv, initialize=True):
		self.N = len(A)
		self.N0 = 2 ** (self.N - 1).bit_length()
		self.intv = intv
		if initialize:
			self.data = [intv] * self.N0 + A + [intv] * (self.N0 - self.N)
			for i in range(self.N0 - 1, 0, -1):
				self.data[i] = self.segf(self.data[2 * i], self.data[2 * i + 1])
		else:
			self.data = [intv] * (2 * self.N0)

	def segf(self, x, y):
		if table[x] > table[y]:
			return x
		else:
			return y

	def update(self, k):
		k += self.N0
		while k > 0:
			k = k >> 1
			self.data[k] = self.segf(self.data[2 * k], self.data[2 * k + 1])

	def query(self, l, r):
		(L, R) = (l + self.N0, r + self.N0)
		s = self.intv
		while L < R:
			if R & 1:
				R -= 1
				s = self.segf(s, self.data[R])
			if L & 1:
				s = self.segf(s, self.data[L])
				L += 1
			L >>= 1
			R >>= 1
		return s

	def binsearch(self, l, r, check, reverse=False):
		(L, R) = (l + self.N0, r + self.N0)
		(SL, SR) = ([], [])
		while L < R:
			if R & 1:
				R -= 1
				SR.append(R)
			if L & 1:
				SL.append(L)
				L += 1
			L >>= 1
			R >>= 1
		if reverse:
			for idx in SR + SL[::-1]:
				if check(self.data[idx]):
					break
			else:
				return -1
			while idx < self.N0:
				if check(self.data[2 * idx + 1]):
					idx = 2 * idx + 1
				else:
					idx = 2 * idx
			return idx - self.N0
		else:
			for idx in SL + SR[::-1]:
				if check(self.data[idx]):
					break
			else:
				return -1
			while idx < self.N0:
				if check(self.data[2 * idx]):
					idx = 2 * idx
				else:
					idx = 2 * idx + 1
			return idx - self.N0

def parorder(Edge, p):
	N = len(Edge)
	par = [0] * N
	par[p] = -1
	stack = [p]
	order = []
	visited = set([p])
	ast = stack.append
	apo = order.append
	while stack:
		vn = stack.pop()
		apo(vn)
		for vf in Edge[vn]:
			if vf in visited:
				continue
			visited.add(vf)
			par[vf] = vn
			ast(vf)
	return (par, order)

def getcld(p):
	res = [[] for _ in range(len(p))]
	for (i, v) in enumerate(p[1:], 1):
		res[v].append(i)
	return res
INF = 10 ** 9 + 7
(N, K) = map(int, readline().split())
Edge = [[] for _ in range(N)]
Dim = [0] * N
for _ in range(N - 1):
	(a, b) = map(int, readline().split())
	a -= 1
	b -= 1
	Edge[a].append(b)
	Edge[b].append(a)
	Dim[a] += 1
	Dim[b] += 1
Dim[0] += 1
(P, L) = parorder(Edge, 0)
dist = [0] * N
for l in L[1:]:
	p = P[l]
	dist[l] = 1 + dist[p]
table = [-INF] * (N + 1)
for i in range(1, N):
	if len(Edge[i]) == 1:
		table[i] = dist[i]
debt = [0] * N
T = Segtree(list(range(N)), N, initialize=True)
ans = 0
N0 = T.N0
for _ in range(K):
	idx = T.query(0, N0)
	ans += table[idx]
	table[idx] = -INF
	T.update(idx)
	if idx == 0:
		break
	p = P[idx]
	Dim[p] -= 1
	debt[p] += -1 + debt[idx]
	if Dim[p] == 1:
		table[p] = dist[p] + debt[p]
		T.update(p)
print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
from collections import deque
(N, K) = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N - 1):
	(x, y) = map(int, input().split())
	X[x - 1].append(y - 1)
	X[y - 1].append(x - 1)
P = [-1] * N
Q = deque([0])
R = []
while Q:
	i = deque.popleft(Q)
	R.append(i)
	for a in X[i]:
		if a != P[i]:
			P[a] = i
			X[a].remove(i)
			deque.append(Q, a)
SIZE = [1] * N
for i in R[1:][::-1]:
	SIZE[P[i]] += SIZE[i]
A = [0] * N
DE = [0] * N
for i in R[1:]:
	DE[i] = DE[P[i]] + 1
for i in R:
	A[i] = (SIZE[i] - DE[i] << 18) + i
A = sorted(A)
T = [0] * N
m = (1 << 18) - 1
for i in A[:K]:
	T[i & m] = 1
ans = 0
B = [0] * N
for i in R[::-1]:
	if T[i]:
		B[P[i]] += B[i] + 1
	else:
		B[P[i]] += B[i]
		ans += B[i]
print(ans)


import sys
from collections import defaultdict
(n, k) = map(int, sys.stdin.readline().strip().split())
g = {}
for _ in range(n - 1):
	(u, v) = map(int, sys.stdin.readline().strip().split())
	if u not in g:
		g[u] = set()
	if v not in g:
		g[v] = set()
	g[u].add(v)
	g[v].add(u)

def solve(n, k, g):
	if n == k:
		return 0
	if n - 1 == k:
		return k
	depth_dict = defaultdict(int)
	parent_dict = defaultdict(int)
	stack = [(-1, 1, 0)]
	leaves = []
	while stack:
		(parent, node, depth) = stack.pop()
		parent_dict[node] = parent
		depth_dict[node] = depth
		child_count = 0
		for e in g[node]:
			if e == parent:
				continue
			stack.append((node, e, depth + 1))
			child_count += 1
		if child_count == 0:
			leaves.append(node)
	count_dict = defaultdict(int)
	event_dict = defaultdict(int)
	while leaves:
		nl = set()
		for node in leaves:
			parent = parent_dict[node]
			if parent == -1:
				continue
			count_dict[parent] += count_dict[node] + 1
			event_dict[parent] += 1
			if event_dict[parent] == len(g[parent]) - 1:
				nl.add(parent)
		leaves = nl
	h = []
	for i in range(1, n + 1):
		h.append(depth_dict[i] - count_dict[i])
	h.sort(reverse=True)
	sum_of_happiness = 0
	for i in range(k):
		sum_of_happiness += h[i]
	return sum_of_happiness
hapiness = solve(n, k, g)
print(hapiness)


import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline
from collections import deque
(n, k) = map(int, input().split())
g = [[] for i in range(n)]
for i in range(n - 1):
	(a, b) = map(int, input().split())
	a -= 1
	b -= 1
	g[a].append(b)
	g[b].append(a)
q = deque([0])
d = [-1] * n
d[0] = 0
w = [-1] * n
ww = [0] * n
while q:
	p = q.popleft()
	for i in g[p]:
		if d[i] == -1:
			d[i] = d[p] + 1
			q.append(i)
			w[i] = p
dp = [1] * n
bb = []
for i in range(1, n):
	bb.append([-d[i], i])
bb.sort()
for i in range(n - 1):
	dp[w[bb[i][1]]] += dp[bb[i][1]]
aa = []
for i in range(n):
	aa.append(d[i] - dp[i] + 1)
aa.sort(reverse=True)
print(sum(aa[:k]))


(n, k) = map(int, input().split(' '))
k = n - k
arr = [[] for i in range(n)]
for i in range(n - 1):
	(a, b) = map(int, input().split(' '))
	arr[a - 1].append(b - 1)
	arr[b - 1].append(a - 1)
visited = [False] * n
stack = [0]
height = [-1] * n
height[0] = 0
while stack:
	temp = stack.pop()
	for i in arr[temp]:
		if height[i] == -1:
			height[i] = height[temp] + 1
			stack.append(i)
nochild = [0] * n
heightsort = [0] * n
for i in range(n):
	heightsort[i] = [height[i], i]
heightsort.sort(reverse=True)
for node in heightsort:
	count = 0
	curr = node[1]
	for i in arr[curr]:
		if height[i] == height[curr] + 1:
			count += nochild[i] + 1
	nochild[curr] = count
nochildsort = []
for i in range(n):
	nochildsort.append(nochild[i] - height[i])
nochildsort.sort(reverse=True)
finalans = 0
for i in range(k):
	finalans += nochildsort[i]
print(finalans)


from sys import stdin, setrecursionlimit
from collections import *
import threading
rints = lambda : [int(x) for x in stdin.readline().split()]
get_col = lambda arr, i: [row[i] for row in arr]

class graph:

	def __init__(self, gdict=None):
		if gdict is None:
			gdict = defaultdict(list)
		(self.gdict, self.edges, self.l) = (gdict, [], defaultdict(int))

	def get_vertices(self):
		return list(self.gdict.keys())

	def addEdge(self, node1, node2, w=None):
		self.gdict[node1].append(node2)
		self.gdict[node2].append(node1)
		self.l[node2] += 1
		self.l[node1] += 1

	def DfsUtil(self, v, lev):
		(self.visit[v], nodes) = (1, 0)
		for i in self.gdict[v]:
			if self.visit[i] == 0:
				nodes += self.DfsUtil(i, lev + 1)
		self.cnt.append(nodes - lev)
		return 1 if self.l[v] == 1 else nodes + 1

	def dfs(self):
		(self.cnt, self.visit) = ([], [0] * (n + 1))
		self.DfsUtil(1, 0)
		return sum(sorted(self.cnt, reverse=True)[:n - k])

def main():
	print(g.dfs())
g = graph()
(n, k) = rints()
for _ in range(n - 1):
	(u, b) = rints()
	g.addEdge(u, b)
setrecursionlimit(10 ** 9)
threading.stack_size(102400000)
thread = threading.Thread(target=main)
thread.start()


import sys
import threading
from collections import defaultdict
(n, k) = map(int, input().split())
adj = defaultdict(list)
for i in range(n - 1):
	(a, b) = map(int, input().split())
	adj[a].append(b)
	adj[b].append(a)
height = [0] * (n + 1)
subtree = [0] * (n + 1)

def dfs(node, par, ht):
	height[node] = ht
	subtree[node] = 1
	for i in range(len(adj[node])):
		if adj[node][i] != par:
			subtree[node] += dfs(adj[node][i], node, ht + 1)
	return subtree[node]

def main():
	dfs(1, 0, 1)
	final = []
	for i in range(1, n + 1):
		final.append(height[i] - subtree[i])
	final.sort(reverse=True)
	ans = 0
	for i in range(k):
		ans += final[i]
	print(ans)
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


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

def prog():
	(n, k) = map(int, input().split())
	adj_list = [[[], 0] for i in range(n + 1)]
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		adj_list[a][0].append(b)
		adj_list[b][0].append(a)
	can_add = []
	subtree = [0 for i in range(n + 1)]
	s = deque([1])
	visited = set()
	while s:
		curr = s[-1]
		visited.add(curr)
		had_neighbor = False
		for i in range(adj_list[curr][1], len(adj_list[curr][0])):
			neighbor = adj_list[curr][0][i]
			if neighbor not in visited:
				had_neighbor = True
				s.append(neighbor)
				adj_list[curr][1] = i + 1
				break
		if not had_neighbor:
			for i in adj_list[curr][0]:
				subtree[curr] += subtree[i]
			subtree[curr] += 1
			can_add.append(len(s) - subtree[curr])
			s.pop()
	can_add.sort(reverse=True)
	happiness = 0
	for i in range(k):
		happiness += can_add[i]
	print(happiness)
prog()


from sys import *
input = stdin.readline
(n, k) = map(int, input().split())
graph = [set([]) for _ in range(n + 1)]
for _ in range(n - 1):
	(x, y) = map(int, input().split())
	graph[x].add(y)
	graph[y].add(x)
(dep, par, cn) = ([0] * (n + 1), [0] * (n + 1), 0)
(q, p) = ([1], [])
vis = [0] * (n + 1)
vis[1] = 1
while q:
	x = q.pop()
	dep[x] = cn
	for i in graph[x]:
		if vis[i] == 0:
			vis[i] = 1
			p.append(i)
			par[i] = x
	if len(q) == 0:
		cn += 1
		q = list(p)
		p = []
tp = []
for i in range(1, n + 1):
	tp.append((i, dep[i]))
tp.sort(key=lambda x: x[1])
tp = tp[::-1]
sub = [0] * (n + 1)
for i in range(len(tp) - 1):
	ind = tp[i][0]
	pid = par[ind]
	sub[pid] += 1 + sub[ind]
a = []
for i in range(1, n + 1):
	a.append(dep[i] - sub[i])
a.sort(reverse=True)
sn = 0
for i in range(k):
	sn += a[i]
stdout.write(str(sn) + '\n')


import collections

def calc():
	(n, k) = map(int, input().split())
	g = [[] for _ in range(n + 1)]
	for _ in range(n - 1):
		(a, b) = map(int, input().split())
		g[a].append(b)
		g[b].append(a)
	q = collections.deque()
	q.append((1, 0))
	checked = [0] * (n + 1)
	checked[1] = 1
	ds = [[] for _ in range(n + 1)]
	pairs = {}
	while len(q) != 0:
		(v, d) = q.popleft()
		ds[d].append(v)
		for u in g[v]:
			if checked[u] == 0:
				checked[u] = 1
				q.append((u, d + 1))
				pairs[u] = v
	cnt = [0] * (n + 1)
	tmp = []
	for i in range(n, 0, -1):
		for v in ds[i]:
			cnt[pairs[v]] += cnt[v] + 1
			tmp.append(i - cnt[v])
	tmp = sorted(tmp, reverse=True)
	print(sum(tmp[:k]))
calc()


import sys
input = sys.stdin.readline
import heapq
import copy
import math

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

class Node:

	def _init_(self, val):
		self.data = val
		self.left = None
		self.right = None

class fen_tree:

	def __init__(self, list):
		self.array = [0] + list
		for idx in range(1, len(self.array)):
			idx2 = idx + (idx & -idx)
			if idx2 < len(self.array):
				self.array[idx2] += self.array[idx]

	def prefix_query(self, idx):
		result = 0
		while idx:
			result += self.array[idx]
			idx -= idx & -idx
		return result

	def prints(self):
		print(self.array)
		return

	def range_query(self, from_idx, to_idx):
		return self.prefix_query(to_idx) - self.prefix_query(from_idx - 1)

	def update(self, idx, add):
		while idx < len(self.array):
			self.array[idx] += add
			idx += idx & -idx

def pre_sum(arr):
	p = [0]
	for i in arr:
		p.append(p[-1] + i)
	p.pop(0)
	return p

def pre_back(arr):
	p = [0]
	for i in arr:
		p.append(p[-1] + i)
	p.pop(0)
	return p

def bin_search(arr, l, r, val):
	if arr[r] <= val:
		return r + 1
	if r - l < 2:
		if arr[l] > val:
			return l
		else:
			return r
	mid = int((l + r) / 2)
	if arr[mid] <= val:
		return bin_search(arr, mid, r, val)
	else:
		return bin_search(arr, l, mid, val)

def search_leftmost(arr, val):

	def helper(arr, l, r, val):
		print(l, r)
		if arr[l] == val:
			return l
		if r - l <= 1:
			if arr[r] == val:
				return r
			else:
				print('not found')
				return
		mid = int((r + l) / 2)
		if arr[mid] >= val:
			return helper(arr, l, mid, val)
		else:
			return helper(arr, mid, r, val)
	return helper(arr, 0, len(arr) - 1, val)

def search_rightmost(arr, val):

	def helper(arr, l, r, val):
		print(l, r)
		if arr[r] == val:
			return r
		if r - l <= 1:
			if arr[l] == val:
				return r
			else:
				print('not found')
				return
		mid = int((r + l) / 2)
		if arr[mid] > val:
			return helper(arr, l, mid, val)
		else:
			return helper(arr, mid, r, val)
	return helper(arr, 0, len(arr) - 1, val)

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = 1
	mod = 1000000007
	limit = 10 ** 18
	for test in range(tests):
		[n, k] = inlt()
		paths = [[] for i in range(n + 1)]
		for i in range(n - 1):
			[s, e] = inlt()
			paths[s].append(e)
			paths[e].append(s)
		parent = [0 for i in range(n + 1)]
		left = [0 for i in range(n + 1)]
		level = [sys.maxsize for i in range(n + 1)]
		level[1] = 0

		def helper(paths, parent, left, level):
			l = 0
			queue = [1]
			while queue != []:
				node = queue[-1]
				flag = 0
				for i in paths[node]:
					if i != parent[node] and level[i] == sys.maxsize:
						parent[i] = node
						level[i] = level[node] + 1
						flag = 1
						queue.append(i)
				if flag == 0:
					left[parent[node]] += 1 + left[node]
					queue.pop()
			return [parent, left, level]
		[parent, left, level] = helper(paths, parent, left, level)
		gain = [level[i] - left[i] for i in range(n + 1)]
		ans = 0
		heap = []
		heapq.heapify(heap)
		done = [0 for i in range(n + 1)]
		for i in range(1, n + 1):
			if left[i] == 0:
				heapq.heappush(heap, [-1 * gain[i], i])
				done[i] = 1
		for i in range(k):
			curr = heapq.heappop(heap)
			ans = ans - curr[0]
			if done[parent[curr[1]]] != 1:
				done[parent[curr[1]]] = 1
				heapq.heappush(heap, [-1 * gain[parent[curr[1]]], parent[curr[1]]])
		print(ans)
main()


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
g = [[] for _ in range(n)]
for i in range(n - 1):
	(u, v) = map(lambda x: int(x) - 1, input().split())
	g[u].append(v)
	g[v].append(u)
lvl = {}
stack = [(0, 0)]
children = [[] for _ in range(n)]
while stack:
	(node, l) = stack.pop()
	lvl[node] = l
	for ne in g[node]:
		if ne not in lvl:
			stack.append((ne, l + 1))
			children[node].append(ne)
subtree = [0] * n
for i in sorted(range(n), key=lambda i: -lvl[i]):
	subtree[i] += 1
	for ch in children[i]:
		subtree[i] += subtree[ch]
print(sum(sorted([lvl[i] - subtree[i] + 1 for i in range(n)], reverse=True)[:k]))


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

def bfs(node):
	depth[node] = 1
	q = deque([node])
	vis[node] = 1
	arr = []
	while q:
		x = q.popleft()
		arr.append(x)
		for j in edge[x]:
			if vis[j] == 0:
				vis[j] = 1
				depth[j] = depth[x] + 1
				child[x].append(j)
				q.append(j)
	arr.reverse()
	return arr
(n, k) = list(map(int, input().split()))
edge = defaultdict(list)
child = defaultdict(list)
vis = [0] * (n + 1)
depth = [0] * (n + 1)
for i in range(n - 1):
	(u, v) = list(map(int, input().split()))
	edge[u].append(v)
	edge[v].append(u)
subTreeSize = [1] * (n + 1)
arr = bfs(1)
for i in arr:
	for j in child[i]:
		subTreeSize[i] += subTreeSize[j]
lis = []
for i in range(1, n + 1):
	lis.append(subTreeSize[i] - depth[i])
lis.sort(reverse=True)
ans = 0
for i in range(n - k):
	ans += lis[i]
print(ans)


import sys
input = sys.stdin.buffer.readline
(n, k) = map(int, input().split())
neig = [0] * n
lev = [0] * n
for i in range(n):
	neig[i] = [0]
	lev[i] = [-1]
lev[0][0] = 0
for i in range(n - 1):
	(a, b) = map(int, input().split())
	a -= 1
	b -= 1
	neig[a][0] += 1
	neig[b][0] += 1
	neig[a].append(b)
	neig[b].append(a)
tod = [0]
while len(tod) > 0:
	foo = tod.pop()
	for i in range(1, neig[foo][0] + 1):
		if lev[neig[foo][i]][0] == -1:
			lev[foo].append(neig[foo][i])
			lev[neig[foo][i]][0] = lev[foo][0] + 1
			lev[neig[foo][i]].append(foo)
			tod.append(neig[foo][i])
upn = [-1] * n
costs = [0] * n
leaves = []
for i in range(n):
	upn[i] = neig[i][0] - 1
	if upn[i] == 0 and i > 0:
		leaves.append(i)
upn[0] = 0
while len(leaves) > 0:
	f = leaves.pop()
	costs[lev[f][1]] += costs[f]
	costs[lev[f][1]] += 1
	upn[lev[f][1]] -= 1
	if upn[lev[f][1]] == 0 and lev[f][0] > 1:
		leaves.append(lev[f][1])
gainz = [0] * n
for i in range(n):
	gainz[i] = lev[i][0] - costs[i]
gainz.sort(reverse=True)
happiness = 0
for i in range(k):
	happiness += gainz[i]
print(happiness)


from collections import deque
[N, K] = list(map(int, input().split()))
connections = [[] for _ in range(N + 1)]
for _ in range(N - 1):
	[U, V] = list(map(int, input().split()))
	connections[U] += (V,)
	connections[V] += (U,)
ordre = []
restants = deque([1])
profondeur = [None] * (N + 1)
profondeur[1] = 0
suivant = [None] * (N + 1)
while restants:
	actuel = restants.popleft()
	ordre += (actuel,)
	for connection in connections[actuel]:
		if profondeur[connection] == None:
			profondeur[connection] = profondeur[actuel] + 1
			restants += (connection,)
			suivant[connection] = actuel
suivants = [0] * (N + 1)
for ville in ordre[N:0:-1]:
	suivants[suivant[ville]] += 1 + suivants[ville]
scores = [profondeur[ville] - suivants[ville] for ville in ordre[1:]]
scores.sort(reverse=True)
print(sum(scores[:K]))


import heapq
import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(n - 1):
	(u, v) = map(int, input().split())
	u -= 1
	v -= 1
	adj[u].append(v)
	adj[v].append(u)
size = [1] * n
s = []
s.append((0, -1, True))
while s:
	(u, p, open) = s.pop()
	if open:
		s.append((u, p, False))
		for v in adj[u]:
			if v != p:
				s.append((v, u, True))
	else:
		for v in adj[u]:
			if v != p:
				size[u] += size[v]
q = []
heapq.heappush(q, (-(size[0] - 1), 0, -1, 0))
res = 0
for _ in range(n - k):
	if not q:
		break
	(d, u, p, a) = heapq.heappop(q)
	res += -d
	for v in adj[u]:
		if v != p:
			a2 = a + 1
			heapq.heappush(q, (-(size[v] - a2 - 1), v, u, a2))
print(res)


import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

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())
import collections as col
import sys
sys.setrecursionlimit(10 ** 5 + 5)
from types import GeneratorType

def solve():

	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 numberOfNodes(s, e):
		subtree[s] = 1
		for u in graph[s]:
			if u == e:
				continue
			yield numberOfNodes(u, s)
			subtree[s] += subtree[u]
		yield

	def bfs(graph, visited, node, queue, visited_dict):
		level = 1
		visited.append((node, level))
		visited_dict[node] = level
		queue = col.deque(queue)
		queue.append((node, level))
		while queue:
			(s, level) = queue.popleft()
			for neighbour in graph[s]:
				if neighbour not in visited_dict:
					visited.append((neighbour, level + 1))
					visited_dict[neighbour] = level + 1
					queue.append((neighbour, level + 1))
		return
	(N, K) = getInts()
	subtree = [0] * (N + 1)
	graph = col.defaultdict(set)
	for n in range(N - 1):
		(x, y) = getInts()
		graph[y].add(x)
		graph[x].add(y)
	root = 1
	numberOfNodes(1, 0)
	(visited, visited_dict) = ([], col.defaultdict(int))
	bfs(graph, visited, root, [], visited_dict)
	nodes = []
	for j in range(2, N + 1):
		nodes.append(visited_dict[j] - subtree[j])
	nodes.sort(reverse=True)
	happiness = 0
	for j in range(K):
		happiness += nodes[j]
	return happiness
ans = solve()
print(ans)


class node:

	def __init__(self, num, depth, son, fa):
		self.num = num
		self.depth = depth
		self.son = son
		self.fa = fa
ls1 = []
sum = 0

def bfs(now):
	ls1.append(node(now, 0, 0, 0))
	for i in ls1:
		now = i.num
		for j in ls[now]:
			ls[j].remove(now)
			ls1.append(node(j, i.depth + 1, 0, now))
(n, k) = map(int, input().split())
ls = [[] for i in range(n + 1)]
for i in range(n - 1):
	(x, y) = map(int, input().split())
	ls[x].append(y)
	ls[y].append(x)
bfs(1)
ls1.reverse()
ls2 = sorted(ls1, key=lambda x: x.num)
for i in ls1:
	if i.fa:
		ls2[i.fa - 1].son += ls2[i.num - 1].son + 1
ls2.sort(key=lambda x: -(x.depth - x.son))
for i in range(k):
	sum += ls2[i].depth - ls2[i].son
print(sum)


import sys
from collections import deque
from heapq import *
input = lambda : sys.stdin.readline().rstrip()
(n, k) = map(int, input().split())
G = [[] for _ in range(n)]
for i in range(1, n):
	(u, v) = map(int, input().split())
	G[u - 1].append(v - 1)
	G[v - 1].append(u - 1)
bfs = [0]
P = [-1 for _ in range(n)]
for cur in bfs:
	for nb in G[cur]:
		del G[nb][G[nb].index(cur)]
		P[nb] = cur
		bfs.append(nb)
SZ = [1] * n
for cur in bfs[1:][::-1]:
	SZ[P[cur]] += SZ[cur]
dep = [1] * n
for cur in bfs[1:]:
	dep[cur] = dep[P[cur]] + 1
sc = [dep[cur] - SZ[cur] for cur in range(n)]
print(sum(sorted(sc, reverse=True)[:k]))


from sys import stdin
import sys, threading

def Soln(node, parent, depth, depthArr, treeArr, sizeArr):
	depthArr[node] = depth
	sizeArr[node] = 1
	for child in treeArr[node]:
		if child != parent:
			sizeArr[node] += Soln(child, node, depth + 1, depthArr, treeArr, sizeArr)
	return sizeArr[node]

def main():
	(n, k) = list(map(int, stdin.readline().rstrip().split(' ')))
	happinessArr = [0] * n
	treeArr = [[] for i in range(n + 1)]
	depthArr = [0] * (n + 1)
	sizeArr = [0] * (n + 1)
	for _ in range(n - 1):
		(x, y) = map(int, input().rstrip().split(' '))
		treeArr[x].append(y)
		treeArr[y].append(x)
	Soln(1, -1, 0, depthArr, treeArr, sizeArr)
	for i in range(n):
		happinessArr[i] = sizeArr[i + 1] - 1 - depthArr[i + 1]
	happinessArr = sorted(happinessArr, reverse=True)
	happiness = 0
	for i in range(n - k):
		happiness += happinessArr[i]
	print(happiness)
sys.setrecursionlimit(2 * 10 ** 5 + 1)
threading.stack_size(128000000)
thread = threading.Thread(target=main)
thread.start()


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
(n, k) = MI()
g = {i: [] for i in range(n + 1)}
for _ in range(n - 1):
	(u, v) = MI()
	g[u].append(v)
	g[v].append(u)
dist = [1 for i in range(n + 1)]
parent = [0 for i in range(n + 1)]
lvl = {i: 0 for i in range(1, n + 1)}
vis = [False for i in range(n + 1)]
(q, i) = ([1], 0)
vis[1] = True
while i < len(q):
	u = q[i]
	for v in g[u]:
		if not vis[v]:
			vis[v] = True
			dist[v] = dist[u] + 1
			parent[v] = u
			lvl[v] = dist[v]
			q.append(v)
	i += 1
sub = [1 for i in range(n + 1)]
for v in sorted(lvl, key=lambda x: lvl[x], reverse=True):
	sub[parent[v]] += sub[v]
ans = {i: 0 for i in range(1, n + 1)}
for v in range(1, n + 1):
	ans[v] = sub[v] - dist[v]
print(sum(sorted(ans.values(), reverse=True)[:n - k]))


import sys
import threading
from collections import defaultdict
(n, k) = list(map(int, input().split()))
adj = defaultdict(list)
for _ in range(n - 1):
	(a, b) = list(map(int, input().split()))
	adj[a].append(b)
	adj[b].append(a)
li = []

def fun(node, par, ht):
	size = 1
	for ch in adj[node]:
		if ch != par:
			size += fun(ch, node, ht + 1)
	li.append(ht - size)
	return size

def main():
	fun(1, -1, 1)
	li.sort(reverse=True)
	print(sum(li[:k]))
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


(n, k) = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(n - 1):
	(u, v) = (int(x) - 1 for x in input().split())
	g[u].append(v)
	g[v].append(u)
depth = [None] * n
depth[0] = 0
size = [None] * n
stack = [0]
while stack:
	u = stack[-1]
	if size[u] is None:
		size[u] = 0
		for v in g[u]:
			if depth[v] is None:
				depth[v] = depth[u] + 1
				stack.append(v)
		continue
	stack.pop()
	size[u] += 1 + sum((size[v] for v in g[u]))
print(sum(sorted((depth[x] - size[x] + 1 for x in range(n)), reverse=True)[:k]))


import collections
from collections import defaultdict
import sys
sys.setrecursionlimit(200000)
input = sys.stdin.readline

def bfs(graph, root):
	visited = set()
	dist = [0] * (n + 1)
	queue = collections.deque([root])
	visited.add(root)
	while queue:
		vertex = queue.popleft()
		for neighbour in graph[vertex]:
			if neighbour not in visited:
				dist[neighbour] = dist[vertex] + 1
				visited.add(neighbour)
				queue.append(neighbour)
	return dist
graph = defaultdict(list)
(n, k) = map(int, input().split())
count1 = [0] * (n + 1)
for i in range(n - 1):
	(u, v) = map(int, input().split())
	graph[u].append(v)
	graph[v].append(u)
ROOT = 1
QUE = [ROOT]
Parent = [-1] * (n + 1)
Parent[ROOT] = 0
topsort = [1]
while QUE:
	x = QUE.pop()
	for to in graph[x]:
		if Parent[to] == -1:
			Parent[to] = x
			QUE.append(to)
			topsort.append(to)
treecount = [1] * (n + 1)
for x in topsort[::-1]:
	treecount[Parent[x]] += treecount[x]
l1 = bfs(graph, 1)
for i in range(len(l1)):
	l1[i] = l1[i] - (treecount[i] - 1)
l1.sort(reverse=True)
suma = sum(l1[:k])
print(suma)


import sys, threading
sys.setrecursionlimit(300000)
threading.stack_size(10 ** 8)

def solve():
	(n, k) = map(int, input().split())
	n1 = [n, k]
	adj = {}
	depths = {}
	cities = []
	subtrees = {}
	nums = {}
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		if a not in adj:
			adj[a] = []
		if b not in adj:
			adj[b] = []
		adj[a].append(b)
		adj[b].append(a)
	v = set()

	def dfs(node, depth):
		v.add(node)
		depths[node] = depth
		subtrees[node] = 0
		for child in adj.get(node, []):
			if child not in v:
				r = dfs(child, depth + 1)
				if type(r) == int:
					subtrees[node] += r
		return subtrees[node] + 1
	dfs(1, 0)
	ans = []
	for i in range(1, n + 1):
		ans.append(depths.get(i, 0) - subtrees.get(i, 0))
	ans.sort(reverse=True)
	print(sum(ans[:k]))
threading.Thread(target=solve).start()


import os
import sys
from io import BytesIO, IOBase
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')
import threading
sys.setrecursionlimit(200000)
threading.stack_size(10 ** 8)

def dfs(x, a):
	global v, d, l, adj
	v[x] = 1
	d[x] = a
	c = 0
	for i in adj[x]:
		if not v[i]:
			c += dfs(i, a + 1) + 1
	l[x] = c
	return l[x]

def main():
	global v, d, l, adj
	(n, k) = map(int, input().split())
	v = [0] * (n + 1)
	l = [0] * (n + 1)
	d = [0] * (n + 1)
	adj = []
	for i in range(n + 1):
		adj.append([])
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		adj[x].append(y)
		adj[y].append(x)
	dfs(1, 0)
	l1 = []
	for i in range(1, n + 1):
		l1.append(l[i] - d[i])
	l1.sort(reverse=True)
	print(sum(l1[:n - k]))
t = threading.Thread(target=main)
t.start()
t.join()


import heapq
import sys
from collections import deque
input = sys.stdin.readline
from types import GeneratorType

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(x, visited, graph, lvl):
	if x not in visited:
		visited.add(x)
		con = lvl
		cnt = 1
		for i in graph[x]:
			if i not in visited:
				e = (yield dfs(i, visited, graph, lvl + 1))
				cnt += e
		node[x] = con - (cnt - 1)
		yield cnt
	yield 0
for _ in range(1):
	(n, k) = map(int, input().split())
	graph = {}
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		if u in graph:
			graph[u].append(v)
		else:
			graph[u] = [v]
		if v in graph:
			graph[v].append(u)
		else:
			graph[v] = [u]
	visited = set()
	node = {}
	dfs(1, visited, graph, 0)
	h = []
	heapq.heapify(h)
	for i in node:
		heapq.heappush(h, -1 * node[i])
	ans = 0
	cnt = 0
	while cnt < k:
		x = -1 * heapq.heappop(h)
		ans += x
		cnt += 1
	print(ans)


import sys
import collections
(n, m) = map(int, sys.stdin.readline().split())
adj = {}
for i in range(n - 1):
	(u, v) = map(int, sys.stdin.readline().split())
	if adj.get(u) == None:
		adj[u] = [v]
	else:
		adj[u].append(v)
	if adj.get(v) == None:
		adj[v] = [u]
	else:
		adj[v].append(u)
visited = {}
queue = collections.deque()
parent = {}
parlist = []
nodes = []
for i in range(1, n + 1):
	visited[i] = 0
visited[1] = 1
queue.append((1, -1, 1))
while len(queue) != 0:
	(node, par, lev) = queue.popleft()
	parent[node] = (par, lev)
	parlist.append((node, lev))
	for each in adj[node]:
		if visited[each] == 0:
			visited[each] = 1
			queue.append((each, node, lev + 1))
parlist.sort(key=lambda i: i[1], reverse=True)
path = {}
cal = []
ans = 0
for (node, lev) in parlist:
	if path.get(node) == None:
		path[node] = 1
	else:
		path[node] += 1
	if path.get(parent[node][0]) == None:
		path[parent[node][0]] = path[node]
	else:
		path[parent[node][0]] += path[node]
for i in range(1, n + 1):
	cal.append(parent[i][1] - path[i])
cal.sort(reverse=True)
for i in range(m):
	ans += cal[i]
print(ans)


from sys import stdin
input = stdin.readline

def dfs():
	size = [0] * n
	parent = [0] * n
	depth = [0] * n
	marked = [False] * n
	stack = [0]
	while stack:
		node = stack[-1]
		if marked[node]:
			stack.pop()
			if node != 0:
				size[parent[node]] += size[node] + 1
			continue
		marked[node] = True
		for neighbor in tree[node]:
			if neighbor == parent[node]:
				continue
			parent[neighbor] = node
			depth[neighbor] = depth[node] + 1
			stack.append(neighbor)
	return (depth, size)
(n, k) = [int(x) for x in input().split()]
tree = [[] for _ in range(n)]
for i in range(n - 1):
	(u, v) = [int(x) for x in input().split()]
	tree[u - 1].append(v - 1)
	tree[v - 1].append(u - 1)
(depth, size) = dfs()
ans = sum(sorted([depth[i] - size[i] for i in range(n)])[-k:])
print(ans)


import sys
input = sys.stdin.readline
from operator import itemgetter
(n, k) = map(int, input().split())
E = [[] for i in range(n + 1)]
for i in range(n - 1):
	(a, b) = map(int, input().split())
	E[a].append(b)
	E[b].append(a)
ROOT = 1
QUE = [ROOT]
Parent = [-1] * (n + 1)
Parent[ROOT] = 0
TOP_SORT = []
while QUE:
	x = QUE.pop()
	TOP_SORT.append(x)
	for to in E[x]:
		if Parent[to] == -1:
			Parent[to] = x
			QUE.append(to)
Children = [1] * (n + 1)
for x in TOP_SORT[::-1]:
	Children[Parent[x]] += Children[x]
from collections import deque
Q = deque()
Q.append(1)
D = [1] * (n + 1)
USE = [0] * (n + 1)
USE[1] = 1
while Q:
	x = Q.pop()
	for to in E[x]:
		if USE[to] == 0:
			Q.append(to)
			USE[to] = 1
			D[to] = D[x] + 1
ANS = 0
POINT = sorted([D[i] - 1 - (Children[i] - 1) for i in range(n + 1)], reverse=True)
print(sum(POINT[:k]))


import threading
from sys import stdin, setrecursionlimit
input = stdin.readline
setrecursionlimit(10 ** 6)
from collections import defaultdict

def dfs(node, parent, g, depth, child):
	depth[node] = depth[parent] + 1
	child[node] = 0
	for e in g[node]:
		if e == parent:
			continue
		child[node] += dfs(e, node, g, depth, child)
	return child[node] + 1

def main():
	(n, k) = map(int, input().strip().split())
	g = defaultdict(list)
	for i in range(n - 1):
		(x, y) = map(int, input().strip().split())
		g[x].append(y)
		g[y].append(x)
	depth = [-1] * (n + 1)
	child = [0] * (n + 1)
	dfs(1, 0, g, depth, child)
	l = list(map(lambda x, y: x - y, depth[1:], child[1:]))
	l = sorted(l, reverse=True)
	print(sum(l[:k]))
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


import sys
import threading
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	t = [[] for i in range(n)]
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		t[u - 1].append(v - 1)
		t[v - 1].append(u - 1)
	d = [0 for i in range(n)]
	s = [1 for i in range(n)]

	def dfs(mae, ima):
		for tsugi in t[ima]:
			if mae != tsugi:
				d[tsugi] = d[ima] + 1
				dfs(ima, tsugi)
		for tsugi in t[ima]:
			if tsugi != mae:
				s[ima] += s[tsugi]
	dfs(-1, 0)
	p = sorted([d[i] - (s[i] - 1) for i in range(n)])[::-1]
	print(sum(p[:k]))
sys.setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


import sys
import collections
import threading
import heapq
import string

def main():
	try:
		(n, k) = map(int, input().split())
		ht = [-1] * n
		st = [0] * n
		g = [[] for i in range(n)]

		def dfs(g, e, h):
			if ht[e] != -1:
				return
			else:
				ht[e] = h
				for i in g[e]:
					dfs(g, i, h + 1)
				s = 0
				for i in g[e]:
					s += st[i]
				st[e] = s + 1
				ht[e] -= st[e]
		for j in range(n - 1):
			(x, y) = map(int, input().split())
			g[x - 1].append(y - 1)
			g[y - 1].append(x - 1)
		dfs(g, 0, 1)
		ht.sort(reverse=True)
		print(sum(ht[:k]))
	except RuntimeError as e:
		print(e)
input = sys.stdin.readline
sys.setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


(n, k) = map(int, input().split())
dict1 = {}
for i in range(1, n + 1):
	dict1[i] = []
for _ in range(n - 1):
	(a, b) = map(int, input().split())
	dict1[a].append(b)
	dict1[b].append(a)
list1 = [1]
floor = [0] * (n + 1)
floor[1] = 1
baohan = [0] * (n + 1)
while list1:
	x = list1.pop()
	for j in dict1[x]:
		if not floor[j]:
			list1.append(j)
			floor[j] = floor[x] + 1
dict2 = {}
s = max(floor)
set1 = set()
for i in range(1, s + 1):
	dict2[i] = []
for i in range(1, n + 1):
	dict2[floor[i]].append(i)
for x in reversed(sorted(list(dict2.keys()))):
	for s in dict2[x]:
		set1.add(s)
		for m in dict1[s]:
			if m in set1:
				baohan[s] += baohan[m] + 1
list3 = [0] * n
for i in range(1, n + 1):
	list3[i - 1] = floor[i] - baohan[i] - 1
list3.sort(reverse=True)
print(sum(list3[:k]))


import math
from collections import Counter, deque
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import threading
from heapq import *

def S():
	return sys.stdin.readline().split()

def I():
	return [int(i) for i in sys.stdin.readline().split()]

def II():
	return int(sys.stdin.readline())

def IS():
	return sys.stdin.readline().replace('\n', '')

def main():
	(n, k) = I()
	tree = [[] for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = I()
		tree[u - 1].append(v - 1)
		tree[v - 1].append(u - 1)
	deap = [0] * n
	size = [0] * n
	visited = [False] * n
	visited[0] = True

	def dfs(x, d):
		s = 1
		deap[x] = d
		for r in tree[x]:
			if not visited[r]:
				visited[r] = True
				s += dfs(r, d + 1)
		size[x] = s - 1
		return s
	dfs(0, 0)
	ans = list(sorted([size[i] - deap[i] for i in range(n)]))
	print(sum(ans[::-1][:n - k]))
threading.stack_size(10 ** 8 + 5)
sys.setrecursionlimit(2 * 10 ** 5 + 10)
threading.Thread(target=main).start()


from sys import *
import collections
import math
(n, k) = list(map(int, stdin.readline().split(' ')))
g = []
for i in range(n + 1):
	g.append([])
for i in range(n - 1):
	(x, y) = list(map(int, stdin.readline().split(' ')))
	g[x].append(y)
	g[y].append(x)
a = []
a = [1]
exp = {}
exp[1] = True
dst = [0] * (n + 1)
root = [0] * (n + 1)
hei = {}
while a:
	u = a.pop()
	h = dst[u] + 1
	for v in g[u]:
		if v not in exp:
			root[v] = u
			dst[v] = h
			if h not in hei:
				hei[h] = []
			hei[h].append(v)
			exp[v] = True
			a.append(v)
val = [1] * (n + 1)
for h in range(n, 0, -1):
	if h not in hei:
		continue
	for x in hei[h]:
		val[root[x]] = val[root[x]] + val[x]
for i in range(1, n + 1, 1):
	dst[i] = dst[i] - val[i] + 1
dst = dst[1:]
dst.sort(reverse=True)
ans = 0
for i in range(k):
	ans += dst[i]
print(ans)


import sys
import math
from bisect import bisect_right as br
import threading

def int_arr():
	return list(map(int, sys.stdin.readline().strip().split()))

def str_arr():
	return list(map(str, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()

def main():
	arr = [-300000 for i in range(200004)]

	def dfs(val, cnt, prev, arr):
		down = 0
		for i in dict[val]:
			if i != prev:
				down += dfs(i, cnt + 1, val, arr)
		arr[val] = cnt - down
		return down + 1
	(n, k) = int_arr()
	dict = {}
	for i in range(1, n):
		(a, b) = int_arr()
		if dict.get(a, 0) == 0:
			dict[a] = [b]
		else:
			dict[a].append(b)
		if dict.get(b, 0) == 0:
			dict[b] = [a]
		else:
			dict[b].append(a)
	dfs(1, 0, -1, arr)
	arr.sort(reverse=True)
	print(sum(arr[:k]))
sys.setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


(n, k) = map(int, input().split())
gs = [[] for _ in range(n + 1)]
for _ in range(n - 1):
	(u, v) = map(int, input().split())
	gs[u].append(v)
	gs[v].append(u)
q = [1]
ccnt = [0] * (n + 1)
ds = [None] * (n + 1)
ds[1] = 0
par = [0] * (n + 1)
par[1] = 0
while q:
	u = q.pop()
	if u < 0:
		ccnt[par[-u]] += ccnt[-u] + 1
		continue
	q.append(-u)
	for v in gs[u]:
		if ds[v] is not None:
			continue
		ds[v] = ds[u] + 1
		par[v] = u
		q.append(v)
srr = (ds[x] - ccnt[x] for x in range(1, n + 1))
sr = sorted(srr, reverse=True)
ans = sum(sr[:k])
print(ans)


from heapq import *
from sys import stdin

class Node:

	def __init__(self, val):
		self.val = val
		self.forw = set()
		self.cou = 0
		self.depth = 0

	def __lt__(self, node):
		return self.cou - self.depth > node.cou - node.depth

	def __str__(self):
		return f'{self.val} {self.forw} {self.cou} {self.depth}'
(n, k) = map(int, stdin.readline().split())
lst1 = [Node(i) for i in range(1, n + 1)]
lst = [Node(i) for i in range(1, n + 1)]
for _ in range(n - 1):
	(u, v) = map(int, stdin.readline().split())
	lst1[u - 1].forw.add(v)
	lst1[v - 1].forw.add(u)
	lst[u - 1].forw.add(v)
	lst[v - 1].forw.add(u)
to = n - k
arr = [1]
while len(arr):
	fl = 0
	for i in lst[arr[-1] - 1].forw:
		lst[i - 1].forw.remove(arr[-1])
		arr.append(i)
		fl = 1
		break
	if fl:
		lst[arr[-2] - 1].forw.remove(i)
	if not fl:
		lst[arr[-1] - 1].depth = len(arr) - 1
		k = lst[arr.pop() - 1].cou + 1
		if len(arr):
			lst[arr[-1] - 1].cou += k
l = [lst[0]]
heapify(l)
ans = 0
se = set()
while to:
	y = heappop(l)
	se.add(y.val)
	ans += y.cou - y.depth
	for t in lst1[y.val - 1].forw:
		if t not in se:
			heappush(l, lst[t - 1])
	to -= 1
print(ans)


import sys
from array import array
from heapq import heappop, heappush

def input():
	return sys.stdin.buffer.readline().decode('utf-8')
(n, k) = map(int, input().split())
deg = [10 ** 9] + [0] * n
adj = [[] for _ in range(n)]
for (u, v) in (map(int, input().split()) for _ in range(n - 1)):
	adj[u - 1].append(v - 1)
	adj[v - 1].append(u - 1)
	(deg[u - 1], deg[v - 1]) = (deg[u - 1] + 1, deg[v - 1] + 1)
subt = [1] * n
stack = [i for i in range(1, n) if deg[i] == 1]
while stack:
	v = stack.pop()
	deg[v] = 0
	for dest in adj[v]:
		if deg[dest] == 0:
			continue
		subt[dest] += subt[v]
		deg[dest] -= 1
		if deg[dest] == 1:
			stack.append(dest)
ans = 0
hq = [(-(subt[0] - 1), 0, 1, -1)]
for _ in range(n - k):
	(score, v, depth, parent) = heappop(hq)
	ans -= score
	for dest in adj[v]:
		if dest == parent:
			continue
		heappush(hq, (depth * subt[dest] - (depth + 1) * (subt[dest] - 1), dest, depth + 1, v))
print(ans)


from collections import defaultdict
import sys
import threading
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
s = []

def dfs(graph, n, p, level):
	penalty = 1
	for c in graph[n]:
		if c == p:
			continue
		penalty += dfs(graph, c, n, level + 1)
	s.append(level - penalty)
	return penalty

def main():
	(n, k) = map(int, input().split())
	g = [[] for i in range(n)]
	for i in range(n - 1):
		(u, v) = map(int, input().split(' '))
		g[u - 1].append(v - 1)
		g[v - 1].append(u - 1)
	try:
		dfs(g, 0, None, 1)
	except Exception as e:
		print(e)
	m = sorted(s, reverse=True)
	print(sum(m[:k]))
t = threading.Thread(target=main)
t.start()
t.join()


import sys
input = sys.stdin.buffer.readline
from types import GeneratorType

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
(n, k) = [int(x) for x in input().split()]
adj = [[] for _ in range(n + 1)]
subTreeSize = [0 for i in range(n + 1)]
depths = [0 for i in range(n + 1)]
for _ in range(n - 1):
	(u, v) = [int(x) for x in input().split()]
	adj[u].append(v)
	adj[v].append(u)

@bootstrap
def dfs(node, p, depth):
	depths[node] = depth
	subtree = 1
	for child in [x for x in adj[node] if x != p]:
		subtree += (yield dfs(child, node, depth + 1))
	subTreeSize[node] = subtree
	yield subtree
dfs(1, 0, 1)
makeTourismBenefit = [0 for _ in range(n + 1)]
for i in range(1, n + 1):
	makeTourismBenefit[i] = -(depths[i] - 1) + (subTreeSize[i] - 1)
makeTourismBenefit.pop(0)
makeTourismBenefit.sort(reverse=True)
print(sum(makeTourismBenefit[:n - k]))


import sys
input = sys.stdin.readline
(n, k) = list(map(int, input().split()))
begin = [-1] * n
end = [-1] * n
hurt = [-1] * n
adj = [[] for i in range(n)]
for _ in range(n - 1):
	(u, v) = list(map(int, input().split()))
	adj[u - 1].append(v - 1)
	adj[v - 1].append(u - 1)
hurt[0] = 1
begin[0] = 0
stack = [0]
curr = 1
while stack:
	nex = stack[-1]
	if adj[nex]:
		v = adj[nex].pop()
		if begin[v] == -1:
			begin[v] = curr
			curr += 1
			stack.append(v)
			hurt[v] = len(stack)
	else:
		end[nex] = curr
		stack.pop()
desc = [end[i] - begin[i] - hurt[i] for i in range(n)]
desc.sort(reverse=True)
out = 0
for i in range(n - k):
	out += desc[i]
print(out)


from collections import deque
import heapq
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = map(int, input().split())
neigh = [[] for i in range(n)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	neigh[u - 1].append(v - 1)
	neigh[v - 1].append(u - 1)
visited = [0 for i in range(n)]
queue = deque()
queue.append([0, 1])
visited[0] = 1
depth = [1] * n
subtree = [0] * n
seq = [0]
while queue:
	[index, d] = queue.popleft()
	for ele in neigh[index]:
		if visited[ele] == 1:
			continue
		visited[ele] = 1
		seq.append(ele)
		depth[ele] = d + 1
		queue.append([ele, d + 1])
heap = []
ans = 0
seq = seq[::-1]
for index in seq:
	subtree[index] = 1
	for ele in neigh[index]:
		subtree[index] += subtree[ele]
	heapq.heappush(heap, depth[index] - subtree[index])
	ans += depth[index] - subtree[index]
	if len(heap) > k:
		ans -= heapq.heappop(heap)
print(ans)


from collections import deque

def readTree(n):
	adj = [set() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		adj[u - 1].add(v - 1)
		adj[v - 1].add(u - 1)
	return adj

def treeOrderByDepth(n, adj, root=0):
	parent = [-2] + [-1] * (n - 1)
	ordered = []
	q = deque()
	q.append(root)
	depth = [0] * n
	while q:
		c = q.popleft()
		ordered.append(c)
		for a in adj[c]:
			if parent[a] == -1:
				parent[a] = c
				depth[a] = depth[c] + 1
				q.append(a)
	return (ordered, parent, depth)
(n, k) = map(int, input().split())
adj = readTree(n)
(ordered, parent, depth) = treeOrderByDepth(n, adj)
children = [0] * n
for nd in ordered[::-1]:
	if parent[nd] != -2:
		children[parent[nd]] += children[nd] + 1
value = list(map(lambda a, b: a - b, depth, children))
value.sort(reverse=True)
print(sum(value[:k]))


def main():
	from sys import stdin
	from sys import stdout
	input = stdin.readline
	print = stdout.write

	def dfs(town_ix, deep=0, parent=0):
		deeps[town_ix] = deep
		if len(kingdom_structure[town_ix]) == 1 and kingdom_structure[town_ix][0] == parent:
			return 1
		for road_to in kingdom_structure[town_ix]:
			if road_to != parent:
				quantity_child[town_ix] += dfs(road_to, deep + 1, town_ix)
		return quantity_child[town_ix] + 1
	(n, k) = list(map(int, input().split()))
	kingdom_structure = [[] for _ in range(n)]
	memo = [list(map(int, input().split())) for _ in range(n - 1)]
	deeps = [0] * n
	quantity_child = [0] * n
	for i in range(n - 1):
		v = memo[i][0] - 1
		u = memo[i][1] - 1
		kingdom_structure[v].append(u)
		kingdom_structure[u].append(v)
	dfs(0)
	towns_profit = sorted([deeps[i] - quantity_child[i] for i in range(n)], reverse=True)
	print(f'{sum(towns_profit[:k])}\n')
from sys import setrecursionlimit
import threading
setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def main():
	(n, k) = map(int, input().split())
	graph = defaultdict(list)
	visited = [False] * n
	dep = [0] * n
	size = [0] * n
	prev = [0] * n

	def DFSUtil(v, visited, b, iu):
		visited[v] = True
		b.append(v)
		prev[v] = len(b)
		if iu == -1:
			dep[v] = 0
		else:
			dep[v] = dep[iu] + 1
		for i in graph[v]:
			if visited[i] == False:
				DFSUtil(i, visited, b, v)
			size[v] = len(b) - prev[v] + 1

	def DFS(v, iu):
		visited = [False] * len(graph)
		b = []
		DFSUtil(v, visited, b, iu)
		return [size, dep]
	e = []
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		graph[u - 1].append(v - 1)
		graph[v - 1].append(u - 1)
	total = DFS(0, -1)
	dis = total[1]
	siz = total[0]
	for i in range(n):
		dep = dis[i]
		size = siz[i]
		e.append(size - dep)
	s = 0
	e.sort(reverse=True)
	for i in range(n - k):
		s = s + e[i] - 1
	print(s)
t = threading.Thread(target=main)
t.start()
t.join()


from sys import stdin
(n, k) = map(int, stdin.readline().split(' '))
k = n - k
arr = [[] for i in range(n)]
for i in range(n - 1):
	(a, b) = map(int, stdin.readline().split(' '))
	arr[a - 1].append(b - 1)
	arr[b - 1].append(a - 1)
visited = [False] * n
stack = [0]
height = [-1] * n
height[0] = 0
while stack:
	temp = stack.pop()
	for i in arr[temp]:
		if height[i] == -1:
			height[i] = height[temp] + 1
			stack.append(i)
nochild = [0] * n
heightsort = [0] * n
for i in range(n):
	heightsort[i] = [height[i], i]
heightsort.sort(reverse=True)
for node in heightsort:
	count = 0
	curr = node[1]
	for i in arr[curr]:
		if height[i] == height[curr] + 1:
			count += nochild[i] + 1
	nochild[curr] = count
nochildsort = []
for i in range(n):
	nochildsort.append([nochild[i] - height[i], i])
nochildsort.sort(reverse=True)
visited = [False] * n
for i in range(k):
	visited[nochildsort[i][1]] = True
finalans = 0
for i in range(k):
	currnode = nochildsort[i][1]
	for j in arr[currnode]:
		if not visited[j]:
			finalans += height[j] * (1 + nochild[j])
print(finalans)


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.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(io.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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from heapq import heapify, heappop
(N, K) = map(int, input().split())
E = [[] for _ in range(N + 1)]
for (u, v) in zip(*[iter(map(int, sys.stdin.read().split()))] * 2):
	E[u].append(v)
	E[v].append(u)
Is_leaf = [True] * (N + 1)
Parent = [None] * (N + 1)
Parent[1] = 0
Depth = [1] * (N + 1)
st = [1]
while st:
	v = st.pop()
	is_leaf = False
	for u in E[v]:
		if Parent[u] is None:
			Parent[u] = v
			Depth[u] = Depth[v] + 1
			st.append(u)
			is_leaf = True
	Is_leaf[v] = is_leaf
Size = [1] * (N + 1)
N_children = [len(ev) - 1 for ev in E]
N_children[1] += 1
st = [v for (v, n_children) in enumerate(N_children[1:], 1) if n_children == 0]
while st:
	v = st.pop()
	p = Parent[v]
	Size[p] += Size[v]
	N_children[p] -= 1
	if N_children[p] == 0:
		st.append(p)
Ans = [Depth[v] - Size[v] for v in range(N + 1)]
Ans[0] = -(1 << 60)
Ans.sort(reverse=True)
print(sum(Ans[:K]))


import math
import sys
from collections import defaultdict, Counter, deque, OrderedDict
import bisect
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]
from itertools import accumulate, groupby
G = defaultdict(list)
first = 0
parents = []
order = []
dis = []

def addEdge(a, b):
	G[a].append(b)
	G[b].append(a)

def DFSutil(node, parents, order, dis):
	my_que = deque()
	my_que.append(node)
	while len(my_que) > 0:
		index = my_que.pop()
		for edge in G.get(index, []):
			if parents[edge] == -2:
				dis[edge] = dis[index] + 1
				my_que.append(edge)
				parents[edge] = index
				order.append(edge)

def findsubtree(first, N):
	parents = [-2 for i in range(N)]
	parents[0] = -1
	order = [0]
	size = [1] * N
	dis = [0] * N
	DFSutil(first, parents, order, dis)
	for z in range(N - 1, 0, -1):
		bb = order[z]
		size[parents[bb]] += size[bb]
	return (size, dis)
first = 0
(N, k) = ilele()
for i in range(N - 1):
	(u, v) = ilele()
	addEdge(u - 1, v - 1)
(a, b) = findsubtree(first, N)
Ans = []
for (i, j) in zip(a, b):
	Ans.append(j - i + 1)
Ans.sort(reverse=True)
print(sum(Ans[:k]))


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	(n, K) = LI()
	uv = [LI_() for _ in range(n - 1)]
	e = [[] for _ in range(n)]
	for (u, v) in uv:
		e[u].append(v)
		e[v].append(u)
	v = [None] * n
	q = [(0, 0)]
	for qi in range(n):
		(u, k) = q[qi]
		v[u] = 1
		for b in e[u]:
			if v[b]:
				continue
			q.append((b, k + 1))
	c = [0] * n
	v = [None] * n
	r = []
	for qi in range(n - 1, -1, -1):
		(u, k) = q[qi]
		v[u] = 1
		for b in e[u]:
			if v[b] is None:
				continue
			c[u] += c[b] + 1
		r.append(k - c[u])
	return sum(sorted(r, reverse=True)[:K])
print(main())


from collections import defaultdict
import sys
import threading
threading.stack_size(2 ** 27)
sys.setrecursionlimit(10 ** 7)

def rl():
	return list(map(int, input().split()))

def ri():
	return int(input())

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

def main():
	(n, k) = rm()
	g = defaultdict(list)
	ns = [0 for i in range(n + 1)]
	hs = [0 for i in range(n + 1)]
	for i in range(n - 1):
		(u, v) = rm()
		g[u].append(v)
		g[v].append(u)

	def f1(u, p):
		a = 1
		for v in g[u]:
			if v != p:
				a += f1(v, u)
		ns[u] = a
		return a

	def f2(u, p, h):
		hs[u] = h
		for v in g[u]:
			if v != p:
				f2(v, u, h + 1)
	f1(1, -1)
	f2(1, -1, 0)
	hn = [hs[i] - ns[i] + 1 for i in range(1, n + 1)]
	hn.sort(reverse=True)
	print(sum(hn[:k]))
threading.Thread(target=main).start()


from collections import defaultdict
import sys, threading
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	gra = defaultdict(list)
	for _ in range(n - 1):
		(s, e) = map(int, input().split())
		gra[s].append(e)
		gra[e].append(s)
	hap = []

	def dfs(n, p, offset):
		sz = 1
		for i in gra[n]:
			if i != p:
				sz += dfs(i, n, offset + 1)
		hap.append(offset - sz)
		return sz
	dfs(1, -1, 1)
	hap.sort(reverse=True)
	count = 0
	for i in range(k):
		count += hap[i]
	print(count)
t = threading.Thread(target=main)
t.start()
t.join()


from queue import PriorityQueue
input = __import__('sys').stdin.readline
(n, k) = map(int, input().split())
e = [[] for i in range(n + 1)]
xe = [0 for i in range(n + 1)]
deg = [0 for i in range(n + 1)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	e[u].append(v)
	e[v].append(u)
	deg[u] += 1
	xe[u] ^= v
	deg[v] += 1
	xe[v] ^= u
c = [0 for i in range(n + 1)]
d = [0 for i in range(n + 1)]
seen = set()
q = [(1, 0)]
while len(q):
	(u, p) = q.pop()
	if u not in seen:
		q.append((u, p))
	for v in e[u]:
		if v != p:
			if u not in seen:
				d[v] = d[u] + 1
				q.append((v, u))
			else:
				c[u] += c[v]
	if u in seen:
		c[u] += 1
	seen.add(u)
values = []
for u in range(1, n + 1):
	x = d[u] - (c[u] - 1)
	values.append(x)
values.sort(reverse=True)
print(sum(values[:k]))
exit()


(n, m) = map(int, input().split())
a = [[] for i in range(n)]
for i in range(n - 1):
	(x, y) = map(int, input().split())
	a[x - 1].append(y - 1)
	a[y - 1].append(x - 1)
ht = [-1 for i in range(n)]
par = [-1 for i in range(n)]
h = 0
stack = [0]
order = []
while stack:
	node = stack.pop()
	order.append(node)
	if ht[node] == -1:
		ht[node] = h
	for i in a[node]:
		if ht[i] == -1:
			par[i] = node
			stack.append(i)
		else:
			ht[node] = ht[i] + 1
score = [0] * n
for i in order[::-1]:
	if par[i] != -1:
		score[par[i]] += 1 + score[i]
for i in range(n):
	score[i] = ht[i] - score[i]
score.sort(reverse=True)
print(sum(score[:m]))


from collections import deque

def readTree(V):
	adj = [set() for i in range(V + 1)]
	for i in range(V - 1):
		(v1, v2) = [int(x) for x in input().split()]
		adj[v1].add(v2)
		adj[v2].add(v1)
	return adj

def happiness(V, k, adj):
	visited = [True, True] + [False] * (V - 1)
	bfs_ordered = [0] * (V + 1)
	depth = [0] * (V + 1)
	father = [0] * (V + 1)
	j = 1
	q = deque()
	q.append(1)
	while q:
		ele = q.popleft()
		bfs_ordered[j] = ele
		j += 1
		for a in adj[ele]:
			if visited[a] == False:
				depth[a] = depth[ele] + 1
				father[a] = ele
				q.append(a)
				visited[a] = True
	return (bfs_ordered, father, depth)
(V, k) = [int(x) for x in input().split()]
adj = readTree(V)
(bfs_ordered, father, depth) = happiness(V, k, adj)
sub_tree_size = [1] * (V + 1)
for ele in bfs_ordered[:1:-1]:
	sub_tree_size[father[ele]] = sub_tree_size[father[ele]] + sub_tree_size[ele]
final = list(map(lambda a, b: a - b + 1, depth, sub_tree_size))
final[0] = -9999999999999999999999999999999
final.sort(reverse=True)
(i, hppy) = (0, 0)
while i < k:
	hppy += final[i]
	i += 1
print(hppy)


from collections import defaultdict
(n, k) = map(int, input().split())
g = {i: [] for i in range(n + 1)}
for i in range(n - 1):
	(u, v) = map(int, input().split())
	g[u].append(v)
	g[v].append(u)
vis = [0] * (n + 1)
st = [[1, 0]]
vis[1] = 1
parent = [-1] * (n + 1)
non = [0] * (n + 1)
noe = defaultdict(int)
while st:
	u = st[-1][0]
	l = st[-1][1]
	ct = 0
	for el in g[u]:
		if vis[el] == 0:
			vis[el] = 1
			ct += 1
			st.append([el, l + 1])
			parent[el] = u
	if ct == 0 and u != 1:
		non[parent[u]] += 1 + non[u]
		st.pop()
		noe[l - non[u]] += 1
	elif ct == 0 and u == 1:
		break
ans = 0
keys = list(noe.keys())
keys.sort()
i = -1
while k > 0:
	ans += keys[i] * min(k, noe[keys[i]])
	k -= min(k, noe[keys[i]])
	i -= 1
print(ans)


(n, k) = map(int, input().split())
roads = {}
nodes = {}
for _ in range(n - 1):
	(u, v) = map(int, input().split())
	roads.setdefault(u, set()).add(v)
	roads.setdefault(v, set()).add(u)
proc = set()
proc_stack = [1]
in_stack = []
chlds = {}
while len(proc_stack) > 0:
	node = proc_stack[-1]
	if node not in proc:
		proc.add(node)
		rds = roads[node] - proc
		chlds[node] = rds
		proc_stack.extend(rds)
		in_stack.append(node)
	else:
		proc_stack.pop()
		in_stack.pop()
		nodes[node] = (len(in_stack), sum((nodes[c][1] for c in chlds[node])) + len(chlds[node]))
print(sum(sorted((n[0] - n[1] for n in nodes.values()), reverse=True)[:k]))


import sys
import collections
(n, k) = map(int, sys.stdin.readline().split())
adj = collections.defaultdict(list)
for i in range(n - 1):
	(u, v) = map(int, sys.stdin.readline().split())
	adj[u].append(v)
	adj[v].append(u)
visited = {}
queue = collections.deque()
parent = {}
parlist = []
nodes = []
for i in range(1, n + 1):
	visited[i] = 0
visited[1] = 1
queue.append((1, -1, 1))
while len(queue) != 0:
	(node, par, lev) = queue.popleft()
	parent[node] = (par, lev)
	parlist.append((node, lev))
	for each in adj[node]:
		if visited[each] == 0:
			visited[each] = 1
			queue.append((each, node, lev + 1))
parlist.sort(key=lambda i: i[1], reverse=True)
path = {}
cal = []
ans = 0
for (node, lev) in parlist:
	if path.get(node) == None:
		path[node] = 1
	else:
		path[node] += 1
	if path.get(parent[node][0]) == None:
		path[parent[node][0]] = path[node]
	else:
		path[parent[node][0]] += path[node]
for i in range(1, n + 1):
	cal.append(parent[i][1] - path[i])
cal.sort(reverse=True)
for i in range(k):
	ans += cal[i]
sys.stdout.write(str(ans))


import sys
import threading
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)

class node:

	def __init__(self):
		self.dist = 0
		self.count = 0
visited = []
edges = []
tree = []

def dfs(pos):
	global visited
	global edges
	global tree
	cnt = 0
	visited[pos] = True
	if edges[pos]:
		for child in edges[pos]:
			if not visited[child]:
				tree[child][0] = tree[pos][0] + 1
				cnt += dfs(child)
	tree[pos][1] = cnt
	return cnt + 1

def main():
	(n, k) = list(map(int, input().split()))
	global visited
	global edges
	global tree
	visited = [False] * (n + 1)
	edges = [[] for i in range(n + 1)]
	tree = [[0, 0] for i in range(n + 1)]
	for i in range(n - 1):
		(a, b) = list(map(int, input().split()))
		edges[a].append(b)
		edges[b].append(a)
	dfs(1)
	ans = sum(sorted([tree[i][0] - tree[i][1] for i in range(1, n + 1)], reverse=True)[:k])
	print(ans)
t = threading.Thread(target=main)
t.start()
t.join()


from collections import deque

def process():
	q = deque()
	q.append(0)
	s = []
	seen = [0] * n
	while len(q) > 0:
		node = q.popleft()
		s.append(node)
		seen[node] = 1
		flag = False
		for c in connections[node]:
			if not seen[c]:
				q.append(c)
				distance[c] = distance[node] + 1
	seen = [0] * n
	while len(s) > 0:
		node = s.pop()
		seen[node] = 1
		for c in connections[node]:
			if not seen[c]:
				children[c] += children[node] + 1
	for i in range(n):
		scores[i] = distance[i] - children[i]
(n, k) = list(map(int, input().split()))
connections = [[] for _ in range(n)]
for i in range(n - 1):
	(u, v) = list(map(int, input().split()))
	connections[u - 1].append(v - 1)
	connections[v - 1].append(u - 1)
scores = [0] * n
distance = [0] * n
children = [0] * n
process()
scores.sort()
print(sum(scores[-k:]))


(n, k) = map(int, input().split())
nodes = [[] for i in range(n)]
for _ in range(n - 1):
	(a, b) = map(int, input().split())
	nodes[a - 1].append(b - 1)
	nodes[b - 1].append(a - 1)
parents = [-2 for i in range(n)]
parents[0] = -1
order = [0]
que = [0]
depth = [0 for i in range(n)]
my_que = [0]
while len(my_que) > 0:
	index = my_que.pop()
	for edge in nodes[index]:
		if parents[edge] == -2:
			my_que.append(edge)
			parents[edge] = index
			depth[edge] = depth[parents[edge]] + 1
			order.append(edge)
size = [1 for i in range(n)]
for z in range(n - 1, 0, -1):
	bb = order[z]
	size[parents[bb]] += size[bb]
score = [size[x] - depth[x] - 1 for x in range(n)]
score.sort(reverse=True)
print(sum(score[:n - k]))


import os
import sys
input = sys.stdin.buffer.readline
from collections import deque
from queue import PriorityQueue
import math

class CF(object):

	def __init__(self):
		(self.n, self.k) = list(map(int, input().split()))
		self.vis = [0] * self.n
		self.r = []
		self.dp = [1] * self.n
		self.h = [0] * self.n
		self.f = [-1] * self.n
		self.g = [[] for _ in range(self.n)]
		for i in range(self.n - 1):
			(x, y) = list(map(int, input().split()))
			x -= 1
			y -= 1
			self.g[x].append(y)
			self.g[y].append(x)
		pass

	def dfs(self):
		s = [0]
		v = [self.g[0]]
		self.vis[0] = 1
		self.h[0] = 0
		while len(s) > 0:
			if v[-1] == []:
				v.pop()
				self.r.append(s.pop())
			else:
				now = v[-1].pop()
				if not self.vis[now]:
					self.vis[now] = 1
					self.h[now] = 1 + self.h[s[-1]]
					self.f[now] = s[-1]
					s.append(now)
					v.append(self.g[now])
		pass

	def gao(self):
		for i in range(self.n - 1):
			self.dp[self.f[self.r[i]]] += self.dp[self.r[i]]
		ans = []
		for i in range(self.n):
			ans.append(self.h[i] - self.dp[i] + 1)
		pass
		ans.sort()
		ans = sum(ans[-self.k:])
		print(ans)

	def main(self):
		self.dfs()
		self.gao()
		pass
cf = CF()
cf.main()
pass


import sys
import heapq as hq
stdin = sys.stdin
ns = lambda : stdin.readline().rstrip()
ni = lambda : int(stdin.readline().rstrip())
nm = lambda : map(int, stdin.readline().split())
nl = lambda : list(map(int, stdin.readline().split()))
(n, k) = nm()
g = [list() for _ in range(n)]
for _ in range(n - 1):
	(a, b) = nm()
	a -= 1
	b -= 1
	g[a].append(b)
	g[b].append(a)
ans = 0
size = [1] * n
dep = [0] * n
par = [-1] * n
dfsl = []
q = [0]
while q:
	v = q.pop()
	dfsl.append(v)
	for x in g[v]:
		if x == par[v]:
			continue
		dep[x] = dep[v] + 1
		par[x] = v
		q.append(x)
for v in reversed(dfsl):
	for x in g[v]:
		if x == par[v]:
			continue
		size[v] += size[x]
m = n - k
ans = 0
q = [(-n + 1, 0)]
for _ in range(m):
	(c, v) = hq.heappop(q)
	ans += c
	for x in g[v]:
		if dep[x] < dep[v]:
			continue
		hq.heappush(q, (dep[x] - size[x] + 1, x))
print(-ans)


import sys
import threading

def main():

	def dfs(v):
		used[v] = True
		cnt[v] = 1
		for i in g[v]:
			if not used[i]:
				h[i] = h[v] + 1
				dfs(i)
				cnt[v] = cnt[v] + cnt[i]
	(n, k) = map(int, input().split())
	used = [False] * (n + 1)
	h = [0] * (n + 1)
	cnt = [0] * (n + 1)
	g = {}
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		if u not in g:
			g[u] = []
		if v not in g:
			g[v] = []
		g[u].append(v)
		g[v].append(u)
	h[1] = 1
	dfs(1)
	val = []
	for i in range(1, n + 1):
		val.append(h[i] - cnt[i])
	val.sort(reverse=True)
	ans = 0
	for i in range(k):
		ans = ans + val[i]
	print(ans)
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


import sys
import collections
import threading
import heapq
import string

def DFS(tree, u, v, A, L, nc):
	for i in tree[u]:
		if i != v:
			L[i] = L[u] + 1
			nc[u] = nc[u] + 1
			DFS(tree, i, u, A, L, nc)
			nc[u] = nc[u] + nc[i]
			A[u][0] = A[u][0] - A[i][1]
	A[u][1] = A[u][1] + (nc[u] + 1) * L[u]
	A[u][0] = A[u][1] + A[u][0]
	return

def main():
	(n, k) = map(int, input().split())
	tree = {}
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		try:
			tree[a].append(b)
		except:
			tree[a] = [b]
		try:
			tree[b].append(a)
		except:
			tree[b] = [a]
	visited = [False for i in range(n + 1)]
	A = [[0, 0] for i in range(n + 1)]
	L = [0 for i in range(n + 1)]
	nc = [0 for i in range(n + 1)]
	DFS(tree, 1, 0, A, L, nc)
	A.pop(0)
	A.sort(reverse=True)
	fc = 0
	for i in range(min(k, len(A))):
		fc = fc + A[i][0]
	print(fc)
	return 0
input = sys.stdin.readline
sys.setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


import sys
import collections
import threading
import heapq
import string

def main():
	try:
		(n, k) = map(int, input().split())
		d = collections.defaultdict(list)
		for i in range(n - 1):
			(u, v) = map(int, input().split())
			d[u].append(v)
			d[v].append(u)
		if k == n:
			print(0)
			return
		if k == n - 1:
			print(k)
			return
		cost = [-1] * n

		def dfs(par, i, cost, h):
			if len(d[i]) == 1 and i > 1:
				cost[i - 1] = -h
				return 1
			ans = 0
			for j in d[i]:
				if j != par:
					ans += dfs(i, j, cost, h + 1)
			cost[i - 1] = ans - h
			return ans + 1
		dfs(0, 1, cost, 0)
		cost.sort()
		print(sum(cost[k:]))
	except RuntimeError as e:
		print(e)
input = sys.stdin.readline
sys.setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


from collections import *

def addGraph(edges):
	tree = defaultdict(list)
	for i in range(edges):
		(u, v) = map(int, input().split())
		tree[u].append(v)
		tree[v].append(u)
	return tree

def bfs(node, order, parent):
	depth = defaultdict(int)
	queue = deque()
	queue.append(node)
	parent[1] = -1
	while queue:
		curr = queue.popleft()
		for i in tree[curr]:
			if i not in parent:
				parent[i] = curr
				depth[i] = depth[curr] + 1
				order.append(i)
				queue.append(i)
	return depth
(n, k) = map(int, input().split())
tree = addGraph(n - 1)
parent = dict()
order = [0, 1]
subTree = defaultdict(int)
depth = bfs(1, order, parent)
for i in range(n, 1, -1):
	curr = order[i]
	subTree[parent[curr]] += subTree[curr] + 1
happiness = []
for i in range(1, n + 1):
	happiness.append(depth[i] - subTree[i])
print(sum(sorted(happiness, reverse=True)[:k]))


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

def bfs(a, b):
	q = deque([(a, b)])
	stack = deque([(a, b)])
	while q:
		(x, p) = q[0]
		q.popleft()
		depth[x] = depth[p] + 1
		size[x] = 1
		for i in l[x]:
			if i == p:
				continue
			q.append((i, x))
			stack.append((i, x))
	while stack:
		(x, p) = stack[-1]
		stack.pop()
		size[p] += size[x]
		ans[x] = depth[x] - size[x]
	size[0] = 0
(n, k) = map(int, input().split())
l = [[] for i in range(n + 1)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	l[u].append(v)
	l[v].append(u)
depth = [0] * (n + 1)
size = [0] * (n + 1)
ans = [0] * (n + 1)
bfs(1, 0)
ans = ans[1:]
ans.sort(reverse=True)
print(sum(ans[:k]))


def dfs(t):
	res = {}
	visited = {1}
	stack = [1]
	depths = {1: 0}
	pcTree = {}
	while stack:
		node = stack[-1]
		if not node in pcTree:
			pcTree[node] = []
		for next_node in t[node]:
			if not next_node in visited:
				depths[next_node] = depths[node] + 1
				stack.append(next_node)
				visited.add(next_node)
				pcTree[node].append(next_node)
		if not t[node]:
			res[node] = 0
		if not node in res:
			res[node] = -1
		else:
			res[node] = sum((res[n] + 1 for n in pcTree[node]))
			stack.pop()
	return (depths, res)
(n, k) = [int(x) for x in input().split()]
tree = {}
for i in range(n - 1):
	(a, b) = [int(x) for x in input().split()]
	if not a in tree:
		tree[a] = []
	if not b in tree:
		tree[b] = []
	tree[a].append(b)
	tree[b].append(a)
(depths, weights) = dfs(tree)
res = [weights[i] - depths[i] for i in range(1, n + 1)]
res.sort(reverse=True)
ans = sum(res[:n - k])
print(ans)


(n, k) = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(n - 1):
	(i, j) = map(lambda i: int(i) - 1, input().split())
	g[i].append(j)
	g[j].append(i)
q = [0]
c = [0] * n
p = [None] + [0] * (n - 1)
d = [0] + [None] * (n - 1)
while True:
	i = q.pop()
	if i == -1:
		break
	j = -(i + 1)
	if j > 0:
		c[p[j]] += c[j] + 1
		continue
	q.append(j)
	for j in g[i]:
		if d[j] is not None:
			continue
		d[j] = d[i] + 1
		p[j] = i
		q.append(j)
sr = sorted([d[i] - c[i] for i in range(n)], reverse=True)
print(sum(sr[:k]))


import sys
from collections import deque

def bfs_search(adj_list, visited, queue, P, d, bfs):
	node = queue.popleft()
	if visited[node]:
		return
	visited[node] = True
	for e in adj_list[node]:
		if visited[e] == False:
			queue.append(e)
			d[e] = d[node] + 1
			P[e] = node
			bfs.append(e)
	return

def answer(n, k, u, v):
	adj_list = [[] for _ in range(n + 1)]
	visited = [False for _ in range(n + 1)]
	for i in range(n - 1):
		adj_list[v[i]].append(u[i])
		adj_list[u[i]].append(v[i])
	queue = deque([1])
	P = [0 for _ in range(n + 1)]
	d = [1 for _ in range(n + 1)]
	bfs = [1]
	while len(queue) > 0:
		bfs_search(adj_list, visited, queue, P, d, bfs)
	SZ = [1 for _ in range(n + 1)]
	for i in range(n - 1, -1, -1):
		c_node = bfs[i]
		SZ[P[c_node]] += SZ[c_node]
	SZmd = []
	for i in range(1, n + 1):
		SZmd.append(SZ[i] - d[i])
	SZmd.sort(reverse=True)
	summ = sum(SZmd[:n - k])
	return summ

def main():
	(n, k) = map(int, sys.stdin.readline().split())
	u = [0 for _ in range(n - 1)]
	v = [0 for _ in range(n - 1)]
	for i in range(n - 1):
		(u[i], v[i]) = map(int, sys.stdin.readline().split())
	print(answer(n, k, u, v))
	return
main()


(n, k) = map(int, input().split())
g = [[] for i in range(n)]
for _ in range(n - 1):
	(x, y) = map(int, input().split())
	g[x - 1].append(y - 1)
	g[y - 1].append(x - 1)
d = [-1] * n
d[0] = 0
q = [[-1, 0, 0]]
while q:
	(par, ver, cnt) = q.pop()
	for to in g[ver]:
		if d[to] == -1:
			d[to] = cnt + 1
			q.append([ver, to, cnt + 1])
subtree_size = [0] * n
stack = [[-1, 0, 0]]
while stack:
	(par, ver, state) = stack.pop()
	if state == 0:
		stack.append([par, ver, 1])
		for to in g[ver]:
			if to != par:
				stack.append([ver, to, 0])
	elif len(g[ver]) == 1:
		subtree_size[ver] = 1
	else:
		cnt = 0
		for to in g[ver]:
			if to != par:
				cnt += subtree_size[to]
		subtree_size[ver] = cnt + 1
arr = [d[i] - subtree_size[i] + 1 for i in range(1, n)]
arr.sort(reverse=True)
print(sum(arr[:k]))


import sys, threading
from collections import defaultdict

def main():
	(n, k) = list(map(int, input().split()))
	tree = defaultdict(list)
	for _ in range(n - 1):
		(u, v) = list(map(int, input().split()))
		tree[u].append(v)
		tree[v].append(u)
	candidates = []

	def dfs(node, depth, p):
		res = 1
		for adj in tree[node]:
			if p == adj:
				continue
			res += dfs(adj, depth + 1, node)
		candidates.append(res - 1 - depth)
		return res
	dfs(1, 0, -1)
	candidates.sort(reverse=True)
	print(sum(candidates[:n - k]))
sys.setrecursionlimit(1 << 30)
threading.stack_size(1 << 27)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


import heapq
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = map(int, input().split())
neigh = [[] for i in range(n)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	neigh[u - 1].append(v - 1)
	neigh[v - 1].append(u - 1)
visited = [0 for i in range(n)]
visited[0] = 1
depth = [1] * n
subtree = [0] * n
seq = [0]
stack = [[0, 1]]
visited = [0] * n
visited[0] = 1
while stack:
	temp = stack.pop()
	[index, d] = temp
	depth[index] = d
	for ele in neigh[index]:
		if visited[ele] == 1:
			continue
		visited[ele] = 1
		stack.append([ele, d + 1])
		seq.append(ele)
heap = []
ans = 0
seq.reverse()
for index in seq:
	subtree[index] = 1
	for ele in neigh[index]:
		subtree[index] += subtree[ele]
	heapq.heappush(heap, depth[index] - subtree[index])
	ans += depth[index] - subtree[index]
	if len(heap) > k:
		ans -= heapq.heappop(heap)
print(ans)


import sys
from types import GeneratorType

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
(n, k) = list(map(lambda x: int(x), input().split()))
from collections import deque

def readTree(n):
	adj = [set() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = map(int, sys.stdin.readline().split())
		adj[u - 1].add(v - 1)
		adj[v - 1].add(u - 1)
	return adj
adj = readTree(n)
dq = deque()
dq.append(0)
parent = [-2] + [-1] * (n - 1)
depth = [0] * n
while dq:
	nd = dq.popleft()
	for a in adj[nd]:
		if parent[a] < 0:
			parent[a] = nd
			depth[a] = depth[nd] + 1
			dq.append(a)
depth[0] = 0
subtree_size = [0 for _ in range(n)]
visited = [False for _ in range(n)]

@bootstrap
def DFSUtil(v, visited):
	global subtree_size
	visited[v] = True
	cnt = 1
	for i in adj[v]:
		if visited[i] == False:
			yield DFSUtil(i, visited)
			cnt += subtree_size[i]
	subtree_size[v] = cnt
	yield
DFSUtil(0, visited)
for i in range(0, len(depth)):
	depth[i] = (i, -subtree_size[i] + depth[i] + 1)
depth.sort(key=lambda x: x[1], reverse=True)
h = 0
print(sum([x[1] for x in depth[0:k]]))


import sys
import threading

def main():
	(n, k) = [int(v) for v in input().split()]
	edges = {}
	for i in range(n - 1):
		(u, w) = [int(v) for v in input().split()]
		if u not in edges:
			edges[u] = set()
		if w not in edges:
			edges[w] = set()
		edges[u].add(w)
		edges[w].add(u)
	visited = set()
	res = []

	def dfs(cur, d):
		visited.add(cur)
		s = 1
		for e in edges.get(cur, []):
			if e not in visited:
				s += dfs(e, d + 1)
		res.append((cur, d - s + 1))
		return s
	dfs(1, 0)
	data = sorted(res, key=lambda b: b[1], reverse=True)
	print(sum([v[1] for v in data[:k]]))
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


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

def tree_traversal(node):
	past_vertexes = set()
	vertexes = [node]
	depths_and_num_of_descendants[node] = [1, 1, 1]
	while vertexes:
		node = vertexes.pop()
		if node in past_vertexes:
			continue
		past_vertexes.add(node)
		for vertex in edges[node]:
			vertexes.append(vertex)
			if vertex not in past_vertexes:
				depths_and_num_of_descendants[vertex] = [depths_and_num_of_descendants[node][0] + 1, 1, node]
(n, k) = map(int, input().split())
edges = defaultdict(list)
for _ in range(n - 1):
	(a, b) = map(int, input().split())
	edges[a].append(b)
	edges[b].append(a)
depths_and_num_of_descendants = {}
tree_traversal(1)
depths_and_num_of_descendants = {key: depths_and_num_of_descendants[key] for key in sorted(depths_and_num_of_descendants, key=lambda key: depths_and_num_of_descendants[key], reverse=True)}
vertexes_with_the_same_depth = []
for node in depths_and_num_of_descendants:
	if not vertexes_with_the_same_depth:
		vertexes_with_the_same_depth.append(node)
	elif depths_and_num_of_descendants[vertexes_with_the_same_depth[0]][0] == depths_and_num_of_descendants[node][0]:
		vertexes_with_the_same_depth.append(node)
	else:
		for vertex in vertexes_with_the_same_depth:
			depths_and_num_of_descendants[depths_and_num_of_descendants[vertex][2]][1] += depths_and_num_of_descendants[vertex][1]
		vertexes_with_the_same_depth = [node]
keys = sorted(depths_and_num_of_descendants, key=lambda key: depths_and_num_of_descendants[key][1] - depths_and_num_of_descendants[key][0])[k:]
print(sum((depths_and_num_of_descendants[key][1] - depths_and_num_of_descendants[key][0] for key in keys)))


import sys
lines = sys.stdin.readlines()
(n, k) = map(int, lines[0].strip().split(' '))
edges = {}
for i in range(1, n):
	(a, b) = map(int, lines[i].strip().split(' '))
	if a not in edges:
		edges[a] = []
	if b not in edges:
		edges[b] = []
	edges[a].append(b)
	edges[b].append(a)
seen = set([1])
stack = [1]
level = {1: 0}
parent = {1: 0}
while stack:
	node = stack.pop()
	for adj in edges[node]:
		if adj not in seen:
			seen.add(adj)
			level[adj] = level[node] + 1
			stack.append(adj)
			parent[adj] = node
noChild = {}
stack = [1]
while stack:
	node = stack.pop()
	all = True
	for adj in edges[node]:
		if adj != parent[node] and adj not in noChild:
			all = False
			break
	if all:
		tmp = 0
		for adj in edges[node]:
			if adj == parent[node]:
				continue
			tmp += noChild[adj] + 1
		noChild[node] = tmp
	else:
		stack.append(node)
		for adj in edges[node]:
			if adj == parent[node]:
				continue
			if adj not in noChild:
				stack.append(adj)
res = [level[i] - noChild[i] for i in range(1, n + 1)]
res.sort(reverse=True)
print(sum(res[:k]))


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7

def dfs():
	stk = [0]
	for i in stk:
		for el in a[i]:
			val[el] += val[i]
			p[el] = i
			del a[el][a[el].index(i)]
			stk += (el,)
	for i in stk[1:][::-1]:
		valn[p[i]] += valn[i]
(n, k) = R()
a = [[] for i in range(n)]
p = [i for i in range(n)]
val = [1] * n
valn = [-1] * n
for i in range(n - 1):
	(x, y) = R()
	a[x - 1] += (y - 1,)
	a[y - 1] += (x - 1,)
dfs()
print(sum(sorted([val[i] + valn[i] for i in range(1, n)], reverse=True)[:k]))


from __future__ import print_function
from collections import Counter, OrderedDict
from itertools import permutations as perm
from fractions import Fraction
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(n, k) = gil()
adj = [[] for _ in range(n + 1)]
for _ in range(n - 1):
	(x, y) = gil()
	adj[x].append(y)
	adj[y].append(x)
(sub, dp) = ([0] * (n + 1), [-1] * (n + 1))
stack = [1]
dp[1] = 0
while stack:
	p = stack.pop()
	for c in adj[p]:
		if dp[c] == -1:
			dp[c] = dp[p] + 1
			stack.append(c)
stack.append(1)
vis = [0] * (n + 1)
fin = [0] * (n + 1)
ans = []
while stack:
	p = stack[-1]
	if vis[p]:
		for c in adj[p]:
			if fin[c]:
				sub[p] += 1 + sub[c]
		fin[p] = 1
		ans.append(dp[p] - sub[p])
		stack.pop()
	else:
		vis[p] = 1
		for c in adj[p]:
			if not vis[c]:
				stack.append(c)
ans.sort(reverse=True)
print(sum(ans[:k]))


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.buffer.readline
	(N, K) = map(int, input().split())
	adj = [[] for _ in range(N + 1)]
	for _ in range(N - 1):
		(a, b) = map(int, input().split())
		adj[a].append(b)
		adj[b].append(a)
	from collections import deque
	que = deque()
	que.append(1)
	seen = [-1] * (N + 1)
	seen[1] = 0
	par = [0] * (N + 1)
	child = [[] for _ in range(N + 1)]
	seq = []
	while que:
		v = que.popleft()
		seq.append(v)
		for u in adj[v]:
			if seen[u] == -1:
				seen[u] = seen[v] + 1
				par[u] = v
				child[v].append(u)
				que.append(u)
	seq.reverse()
	dp = [1] * (N + 1)
	for v in seq:
		for u in child[v]:
			dp[v] += dp[u]
	A = []
	for v in range(1, N + 1):
		A.append(seen[v] - (dp[v] - 1))
	A.sort(reverse=True)
	ans = 0
	for i in range(K):
		ans += A[i]
	print(ans)
main()


from sys import stdin
input = stdin.readline
(n, k) = [int(x) for x in input().split()]
a = [[int(x) for x in input().split()] for _ in range(n - 1)]
b = [[] for x in range(n)]
for (u, v) in a:
	b[u - 1].append(v - 1)
	b[v - 1].append(u - 1)
marked = [False] * n
depth = [0] * n
childs = [0] * n
stack = []
stack.append((0, 0))
while stack:
	(z, f) = stack[-1]
	if marked[z]:
		stack.pop()
		if z != 0:
			childs[f] += childs[z] + 1
		continue
	marked[z] = True
	neighbors = b[z]
	for i in neighbors:
		if not marked[i]:
			depth[i] = depth[z] + 1
			stack.append((i, z))
ans = sum(sorted([depth[i] - childs[i] for i in range(n)])[-k:])
print(ans)


(n, k) = map(int, input().split())
l = {i + 1: [] for i in range(n)}
for _ in range(n - 1):
	(a, b) = map(int, input().split())
	l[a].append(b)
	l[b].append(a)
d = {i + 1: -1 for i in range(n)}
d[1] = 0
q = [1]
while q:
	q1 = []
	for a in q:
		for b in l[a]:
			if d[b] == -1:
				d[b] = d[a] + 1
				q1.append(b)
	q = q1
ind = {i + 1: 0 for i in range(n)}
ind[1] = len(l[1])
for i in range(2, n + 1):
	ind[i] = len(l[i]) - 1
size = {i + 1: 0 for i in range(n)}
q = []
for i in range(1, n + 1):
	if ind[i] == 0:
		q.append(i)
		ind[i] = -1
while q:
	q1 = []
	for a in q:
		for b in l[a]:
			if d[a] == d[b] + 1:
				size[b] += size[a] + 1
				ind[b] -= 1
				if ind[b] == 0:
					q1.append(b)
	q = q1
x = []
for i in range(1, n + 1):
	x.append(d[i] - size[i])
x = sorted(x)
print(sum(x[n - k:]))


import sys
import threading
from collections import defaultdict
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	tree = defaultdict(list)
	for edge in range(n - 1):
		(u, v) = map(int, input().split())
		tree[u].append(v)
		tree[v].append(u)
	res = []

	def dfs(cn, p, d):
		sz = 1
		for nn in tree[cn]:
			if nn != p:
				sz += dfs(nn, cn, d + 1)
		res.append(d - sz)
		return sz
	dfs(1, -1, 1)
	res.sort(reverse=True)
	ans = 0
	for i in range(k):
		ans += res[i]
	print(ans)
t = threading.Thread(target=main)
t.start()
t.join()