#include <bits/stdc++.h> using namespace std; int n, m; vector<vector<int>> graph; vector<int> w; long long cost; pair<int, int> dfs(int u, int parent) { if (u < m) return make_pair(w[u], w[u]); vector<int> temp; for (int v : graph[u]) if (v != parent) { int a, b; tie(a, b) = dfs(v, u); temp.push_back(a); temp.push_back(b); cost -= (b - a); } sort(temp.begin(), temp.end()); for (int i = 0; i < temp.size(); ++i) cost += abs(temp[temp.size() / 2] - temp[i]); return make_pair(temp[temp.size() / 2 - 1], temp[temp.size() / 2]); } int main() { ios_base::sync_with_stdio(false); cin >> n >> m; graph.resize(n); for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; --a; --b; graph[a].push_back(b); graph[b].push_back(a); } w.resize(m); for (int i = 0; i < m; ++i) cin >> w[i]; if (n == m) { assert(n == 2); cout << abs(w[0] - w[1]) << endl; return 0; } cost = 0; dfs(m, -1); cost /= 2; cout << cost << endl; }
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 | #include <bits/stdc++.h> using namespace std; int n, m; vector<vector<int>> graph; vector<int> w; long long cost; pair<int, int> dfs(int u, int parent) { if (u < m) return make_pair(w[u], w[u]); vector<int> temp; for (int v : graph[u]) if (v != parent) { int a, b; tie(a, b) = dfs(v, u); temp.push_back(a); temp.push_back(b); cost -= (b - a); } sort(temp.begin(), temp.end()); for (int i = 0; i < temp.size(); ++i) cost += abs(temp[temp.size() / 2] - temp[i]); return make_pair(temp[temp.size() / 2 - 1], temp[temp.size() / 2]); } int main() { ios_base::sync_with_stdio(false); cin >> n >> m; graph.resize(n); for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; --a; --b; graph[a].push_back(b); graph[b].push_back(a); } w.resize(m); for (int i = 0; i < m; ++i) cin >> w[i]; if (n == m) { assert(n == 2); cout << abs(w[0] - w[1]) << endl; return 0; } cost = 0; dfs(m, -1); cost /= 2; cout << cost << endl; } |