Vlad and Unfinished Business (Codeforces 1675F)
Tags: Greedy, trees

Vlad and Nastya live in a city consisting of $$$n$$$ houses and $$$n-1$$$ road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree.Vlad lives in a house with index $$$x$$$, and Nastya lives in a house with index $$$y$$$. Vlad decided to visit Nastya. However, he remembered that he had postponed for later $$$k$$$ things that he has to do before coming to Nastya. To do the $$$i$$$-th thing, he needs to come to the $$$a_i$$$-th house, things can be done in any order. In $$$1$$$ minute, he can walk from one house to another if they are connected by a road.Vlad does not really like walking, so he is interested what is the minimum number of minutes he has to spend on the road to do all things and then come to Nastya. Houses $$$a_1, a_2, \dots, a_k$$$ he can visit in any order. He can visit any house multiple times (if he wants).

Input: The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. There is an empty line before each test case.The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of houses and things, respectively.The second line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — indices of the houses where Vlad and Nastya live, respectively.The third line of each test case contains $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ ($$$1 \le a_i \le n$$$) — indices of houses Vlad need to come to do things.The following $$$n-1$$$ lines contain description of city, each line contains two integers $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — indices of houses connected by road $$$j$$$.It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2\cdot10^5$$$.

Output: Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer output single integer — the minimum number of minutes Vlad needs on the road to do all the things and come to Nastya.

Note: Tree and best path for the first test case:  $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$ Tree and best path for the second test case:  $$$3 \rightarrow 1 \rightarrow 3 \rightarrow 5 \rightarrow 2 \rightarrow 5 \rightarrow 6 \rightarrow 5$$$ Tree and best path for the third test case:  $$$3 \rightarrow 5 \rightarrow 2$$$ 

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

Sample Outputs:
3
7
2

Solution (Python):
from sys import stdin

def s(n, x, y, a, g):
    a.add(y)
    a.add(x)
    h = 0
    q = [(x - 1, 0)]
    vis = [False for i in range(n)]
    p = [-1 for i in range(n)]
    while q:
        (v, d) = q.pop()
        vis[v] = True
        if v == y - 1:
            h = d
        for w in g[v]:
            if vis[w] == False:
                p[w] = v
                q.append((w, d + 1))
    an = list(a)
    ans = 0
    for w in an:
        if w != x and p[w - 1] + 1 not in a:
            a.add(p[w - 1] + 1)
            an += [p[w - 1] + 1]
        if w != x:
            ans += 2
    return ans - h
for _ in range(int(stdin.readline())):
    input()
    (n, k) = map(int, stdin.readline().split())
    (x, y) = map(int, stdin.readline().split())
    a = set(map(int, stdin.readline().split()))
    g = [[] for f in range(n)]
    for i in range(n - 1):
        (u, v) = map(int, stdin.readline().split())
        g[u - 1].append(v - 1)
        g[v - 1].append(u - 1)
    print(s(n, x, y, a, g))

Solution (Python):
def solve(n, k, x, y, a, graph):
    a.add(x)
    a.add(y)
    stack = [(x, 0)]
    parent = (n + 1) * [-1]
    y_height = None
    while stack:
        (node, height) = stack.pop()
        if node == y:
            y_height = height
        for child in graph[node]:
            if child != parent[node]:
                parent[child] = node
                stack.append((child, height + 1))
    lst = list(a)
    edge_ct = 0
    for node in lst:
        if node != x and parent[node] not in a:
            a.add(parent[node])
            lst.append(parent[node])
        if node != x:
            edge_ct += 2
    return edge_ct - y_height
t = int(input())
for case in range(t):
    input()
    (n, k) = map(int, input().split())
    (x, y) = map(int, input().split())
    a = set(map(int, input().split()))
    graph = [[] for _ in range(n + 1)]
    for _ in range(n - 1):
        (u, v) = map(int, input().split())
        graph[u].append(v)
        graph[v].append(u)
    print(solve(n, k, x, y, a, graph))

Solution (Python):
import sys
input = sys.stdin.readline
import math
sys.setrecursionlimit(200020)
import threading
threading.stack_size(2 ** 27)

def main():
    for _ in range(int(input())):
        line = input()
        (N, K) = map(int, input().split())
        (X, Y) = map(int, input().split())
        Nodes = set(map(int, input().split()))
        Nodes.add(X)
        Nodes.add(Y)
        Graph = []
        for i in range(N + 1):
            Graph.append([])
        for i in range(N - 1):
            (A, B) = map(int, input().split())
            Graph[A].append(B)
            Graph[B].append(A)
        visited = [False] * (N + 1)
        dist = [10 ** 6] * (N + 1)
        total = [0]

        def DFS(node):
            visited[node] = True
            found = False
            for nie in Graph[node]:
                if not visited[nie]:
                    dist[nie] = min(dist[nie], dist[node] + 1)
                    good = DFS(nie)
                    if good:
                        total[0] = total[0] + 2
                    found = found or good
            if node in Nodes:
                return True
            else:
                return found
        dist[X] = 0
        DFS(X)
        print(total[0] - dist[Y])
threading.Thread(target=main).start()