Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.StringTokenizer;
- import java.util.ArrayList;
- //https://pastebin.com/vaXQ31LR
- public class ccc16s3 {
- static int n, k, ans, max = 0, p;
- static boolean good[] = new boolean[200005];
- static ArrayList<Integer> adj[] = new ArrayList[200005];
- static void dfs(int N, int P){
- for (int l = 0; l < adj[N].size(); ++l){
- int next = adj[N].get(l);
- if (next == P) continue;
- dfs(next, N);
- good[N] |= good[next];
- if (good[next]) ans ++;
- }
- }
- static void get_dis(int N, int P, int D){
- if (!good[N]) return;
- for (int l = 0; l < adj[N].size(); ++l){
- int next = adj[N].get(l);
- if (next == P) continue;
- get_dis(next, N, D + 1);
- }
- if (D > max){
- p = N;
- max = D;
- }
- }
- public static void main(String[] args)
- {
- FastReader in = new FastReader();
- n = in.nextInt(); k = in.nextInt();
- for (int l = 0; l <= n; ++ l){
- adj[l] = new ArrayList<Integer>();
- }
- int a = 0;
- for (int l = 0; l < k; ++l){
- a = in.nextInt();
- good[a] = true;
- }
- int start = a;
- for (int l = 0; l < n - 1; ++l){
- a = in.nextInt(); int b = in.nextInt();
- adj[a].add(b);
- adj[b].add(a);
- }
- dfs(start, -1);
- get_dis(start, -1, 0);
- get_dis(p, -1, 0);
- //System.out.println(max);
- System.out.println(ans * 2 - max);
- }
- static class FastReader {
- BufferedReader br;
- StringTokenizer st;
- public FastReader(){
- br = new BufferedReader(new
- InputStreamReader(System.in));
- }
- String next(){
- while (st == null || !st.hasMoreElements()){
- try {
- st = new StringTokenizer(br.readLine());
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- return st.nextToken();
- }
- int nextInt()
- {
- return Integer.parseInt(next());
- }
- long nextLong()
- {
- return Long.parseLong(next());
- }
- double nextDouble()
- {
- return Double.parseDouble(next());
- }
- String nextLine() {
- String str = "";
- try {
- str = br.readLine();
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- return str;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement