1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct stacja{
	int r;
	vector<int> g;
	vector<int> c;
	int dif;
};

int n, m, a, b, sum;
stacja data[500003];
bool vis[500003];
vector<int> w;
int med;

int dfs(int v){
	vis[v] = true;
	if(data[v].r) return data[v].r;
	else{
		data[v].dif = 10000009;
		for(int i = 0; i < data[v].g.size(); ++i){
			if(!vis[data[v].g[i]]){
				a = dfs(data[v].g[i]);
				data[v].c.push_back(a);
			}
		}
		sort(data[v].c.begin(), data[v].c.end());
		data[v].dif = data[v].c[data[v].c.size()/2];
		for(int i = 0; i < data[v].c.size(); ++i){
			if(data[v].c.size() > 1)sum += abs(data[v].dif-data[v].c[i]);
		}
	}
	return data[v].dif;
	
}

int main(){
	ios_base::sync_with_stdio(0);
	cin >> n >> m;
	for(int i = 1; i < n; ++i){
		cin >> a >> b;
		data[a].g.push_back(b);
		data[b].g.push_back(a);
	}
	for(int i = 1; i <= m; ++i){
		cin >> a;
		w.push_back(a);
		data[i].r = a;
	}
	sort(w.begin(), w.end());
	med = w[w.size()/2];
	dfs(n);
	cout << sum << endl;
	return 0;
}