Linova and Kingdom (Codeforces 1337C)
Tags: Greedy, trees

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. 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.

Note: 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.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$$$.

Sample Inputs:
7 4
1 2
1 3
1 4
3 5
3 6
4 7

4 1
1 2
1 3
2 4

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

Sample Outputs:
7

2

9

Solution (Python):
from sys import stdin, setrecursionlimit
input = stdin.readline
setrecursionlimit(5 * 10 ** 5)
import threading

def dfs(p, prev, lvl):
    dist[p - 1] = lvl
    x = 1
    for i in child[p]:
        if i != prev:
            x += dfs(i, p, lvl + 1)
    dist[p - 1] -= x
    return x

def answer(k):
    dist.sort(reverse=True)
    ans = 0
    for i in range(k):
        ans += dist[i]
    return ans
(child, dist) = ([], [])

def main():
    global child, dist
    (n, k) = map(int, input().split())
    child = [[] for i in range(n + 1)]
    for i in range(n - 1):
        (u, v) = map(int, input().split())
        child[u].append(v)
        child[v].append(u)
    dist = [0] * n
    dfs(1, -1, 1)
    print(answer(k))
if __name__ == '__main__':
    threading.stack_size(1 << 27)
    thread = threading.Thread(target=main)
    thread.start()
    thread.join()

Solution (Python):
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()

Solution (Python):
from sys import stdin, setrecursionlimit
input = stdin.readline
import threading

def dfs(p, prev, lvl):
    dist[p - 1] = lvl
    x = 1
    for i in child[p]:
        if i != prev:
            x += dfs(i, p, lvl + 1)
    dist[p - 1] -= x
    return x

def answer(k):
    dist.sort(reverse=True)
    ans = 0
    for i in range(k):
        ans += dist[i]
    return ans
(child, dist) = ([], [])

def main():
    global child, dist
    (n, k) = map(int, input().split())
    child = [[] for i in range(n + 1)]
    for i in range(n - 1):
        (u, v) = map(int, input().split())
        child[u].append(v)
        child[v].append(u)
    dist = [0] * n
    dfs(1, -1, 1)
    print(answer(k))
if __name__ == '__main__':
    setrecursionlimit(10 ** 6)
    threading.stack_size(1 << 27)
    thread = threading.Thread(target=main)
    thread.start()
    thread.join()