Sonya and Ice Cream (Codeforces 1004E)
Tags: Greedy, shortest paths

Sonya likes ice cream very much. She eats it even during programming competitions. That is why the girl decided that she wants to open her own ice cream shops.Sonya lives in a city with $$$n$$$ junctions and $$$n-1$$$ streets between them. All streets are two-way and connect two junctions. It is possible to travel from any junction to any other using one or more streets. City Hall allows opening shops only on junctions. The girl cannot open shops in the middle of streets. Sonya has exactly $$$k$$$ friends whom she can trust. If she opens a shop, one of her friends has to work there and not to allow anybody to eat an ice cream not paying for it. Since Sonya does not want to skip an important competition, she will not work in shops personally.Sonya wants all her ice cream shops to form a simple path of the length $$$r$$$ ($$$1 \le r \le k$$$), i.e. to be located in different junctions $$$f_1, f_2, \dots, f_r$$$ and there is street between $$$f_i$$$ and $$$f_{i+1}$$$ for each $$$i$$$ from $$$1$$$ to $$$r-1$$$.The girl takes care of potential buyers, so she also wants to minimize the maximum distance between the junctions to the nearest ice cream shop. The distance between two junctions $$$a$$$ and $$$b$$$ is equal to the sum of all the street lengths that you need to pass to get from the junction $$$a$$$ to the junction $$$b$$$. So Sonya wants to minimize$$$$$$\max_{a} \min_{1 \le i \le r} d_{a,f_i}$$$$$$where $$$a$$$ takes a value of all possible $$$n$$$ junctions, $$$f_i$$$ — the junction where the $$$i$$$-th Sonya's shop is located, and $$$d_{x,y}$$$ — the distance between the junctions $$$x$$$ and $$$y$$$.Sonya is not sure that she can find the optimal shops locations, that is why she is asking you to help her to open not more than $$$k$$$ shops that will form a simple path and the maximum distance between any junction and the nearest shop would be minimal. 

Input: The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\leq k\leq n\leq 10^5$$$) — the number of junctions and friends respectively.Each of the next $$$n-1$$$ lines contains three integers $$$u_i$$$, $$$v_i$$$, and $$$d_i$$$ ($$$1\leq u_i, v_i\leq n$$$, $$$v_i\neq u_i$$$, $$$1\leq d\leq 10^4$$$) — junctions that are connected by a street and the length of this street. It is guaranteed that each pair of junctions is connected by at most one street. It is guaranteed that you can get from any junctions to any other.

Output: Print one number — the minimal possible maximum distance that you need to pass to get from any junction to the nearest ice cream shop. Sonya's shops must form a simple path and the number of shops must be at most $$$k$$$.

Note: In the first example, you can choose the path 2-4, so the answer will be 4.  The first example. In the second example, you can choose the path 4-1-2, so the answer will be 7.  The second example. 

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

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

Sample Outputs:
4

7

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def make_graph(n, m):
    (x, y, s) = ([0] * (2 * m), [0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        (u, v, w) = map(int, input().split())
        s[u + 2] += 1
        s[v + 2] += 1
        (x[i], x[i + 1]) = (u, v)
        (y[i], y[i + 1]) = (w, w)
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    (G, W) = ([0] * (2 * m), [0] * (2 * m))
    for i in range(2 * m):
        j = x[i] + 1
        G[s[j]] = x[i ^ 1]
        W[s[j]] = y[i ^ 1]
        s[j] += 1
    return (G, W, s)

def binary_search(c1, c2):
    m = (c1 + c2 + 1) // 2
    while abs(c1 - c2) > 1:
        m = (c1 + c2 + 1) // 2
        if ok(m):
            c2 = m
        else:
            c1 = m
    m -= 1
    while not ok(m):
        m += 1
    return m

def ok(m):
    (q, l) = (list(q0), 0)
    c = list(c0)
    dp = [0] * (n + 1)
    while len(q) ^ l:
        i = q[l]
        if not c[i]:
            l += 1
            continue
        dpi = dp[i]
        for v in range(s0[i], s0[i + 1]):
            (j, w) = (G[v], W[v])
            if dpi + w > m or c[j] <= 0:
                continue
            dp[j] = max(dp[j], dpi + w)
            c[i] -= 1
            c[j] -= 1
            if c[j] <= 1:
                q.append(j)
        l += 1
    s = 0
    u = []
    for i in range(1, n + 1):
        if c[i] > 0:
            s += 1
            x = 0
            for v in range(s0[i], s0[i + 1]):
                j = G[v]
                if c[j] > 0:
                    x += 1
            if s > k or x >= 3:
                return False
            u.append(x)
    if len(u) == 1 and (not x):
        return True
    c1 = 0
    for i in u:
        if i == 1:
            c1 += 1
        elif not i:
            return False
    return True if c1 <= 2 else False
(n, k) = map(int, input().split())
(G, W, s0) = make_graph(n, n - 1)
(q0, c0) = ([], [0] * (n + 1))
for i in range(1, n + 1):
    c0[i] = s0[i + 1] - s0[i]
    if s0[i + 1] - s0[i] == 1:
        q0.append(i)
inf = pow(10, 9) + 1
ans = binary_search(0, inf)
print(ans)

Solution (Python):
import heapq
(n, k) = map(int, input().split())
g = [{} for _ in range(n)]
for i in range(n - 1):
    (u, v, d) = map(int, input().split())
    u -= 1
    v -= 1
    g[u][v] = g[v][u] = d
q = [(sum(g[i].values()), i) for i in range(n) if len(g[i]) == 1]
heapq.heapify(q)
D = 0
while not (n <= k and len(q) <= 2):
    (D, u) = heapq.heappop(q)
    (v, _) = g[u].popitem()
    del g[v][u]
    if len(g[v]) == 1:
        heapq.heappush(q, (D + sum(g[v].values()), v))
    n -= 1
print(D)

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def make_graph(n, m):
    (x, y, s) = ([0] * (2 * m), [0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        (u, v, w) = map(int, input().split())
        s[u + 2] += 1
        s[v + 2] += 1
        (x[i], x[i + 1]) = (u, v)
        (y[i], y[i + 1]) = (w, w)
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    (G, W) = ([0] * (2 * m), [0] * (2 * m))
    for i in range(2 * m):
        j = x[i] + 1
        G[s[j]] = x[i ^ 1]
        W[s[j]] = y[i ^ 1]
        s[j] += 1
    return (G, W, s)

def binary_search(c1, c2):
    m = (c1 + c2 + 1) // 2
    while abs(c1 - c2) > 1:
        m = (c1 + c2 + 1) // 2
        if ok(m):
            c2 = m
        else:
            c1 = m
    m -= 1
    while not ok(m):
        m += 1
    return m

def ok(m):
    (q, l) = (list(q0), 0)
    c = list(c0)
    dp = [0] * (n + 1)
    while len(q) ^ l:
        i = q[l]
        if not c[i]:
            l += 1
            continue
        dpi = dp[i]
        for v in range(s0[i], s0[i + 1]):
            (j, w) = (G[v], W[v])
            if dpi + w > m or c[j] <= 0:
                continue
            dp[j] = max(dp[j], dpi + w)
            c[i] -= 1
            c[j] -= 1
            if c[j] <= 1:
                q.append(j)
        l += 1
    s = 0
    u = []
    for i in range(1, n + 1):
        if c[i] > 0:
            s += 1
            x = 0
            for v in range(s0[i], s0[i + 1]):
                j = G[v]
                if c[j] > 0:
                    x += 1
            if s > k or x >= 3:
                return False
            u.append(x)
    if len(u) == 1 and (not x):
        return True
    c1 = 0
    for i in u:
        if i == 1:
            c1 += 1
        elif not i:
            return False
    return True if c1 <= 2 else False
(n, k) = map(int, input().split())
(G, W, s0) = make_graph(n, n - 1)
(q0, c0) = ([], [0] * (n + 1))
for i in range(1, n + 1):
    c0[i] = s0[i + 1] - s0[i]
    if s0[i + 1] - s0[i] == 1:
        q0.append(i)
inf = pow(10, 9) + 1
ans = binary_search(0, inf)
print(ans)