原题传送门
直接贪心就好啦
对于某一条边,如果他的左边有
x
x
x个大学,右边有
y
y
y个大学
那么他对答案的贡献是一定的:
m
i
n
(
x
,
y
)
min(x,y)
min(x,y)
发现
x
,
y
x,y
x,y还有一个等式:
x
+
y
=
2
k
x+y=2k
x+y=2k
好了,我们只需要遍历一遍,并且求出一个点某一个方向的大学个数即可(另一个方向直接用2k去减)
Code:
#include <bits/stdc++.h>
#define maxn 200010
#define int long long
using namespace std;
struct Edge{
int to, next;
}edge[maxn << 1];
int n, k, ans, num, head[maxn], dis[maxn];
inline int read(){
int s = 0, w = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
return s * w;
}
void addedge(int x, int y){ edge[++num] = (Edge){ y, head[x] }; head[x] = num; }
#define v edge[i].to
void dfs(int u, int pre){
for (int i = head[u]; i; i = edge[i].next) if (v != pre) dfs(v, u), dis[u] += dis[v];
for (int i = head[u]; i; i = edge[i].next) if (v != pre) ans += min(dis[v], k - dis[v]);
}
signed main(){
n = read(), k = read();
k <<= 1;
for (int i = 1; i <= k; ++i){
int x = read(); dis[x] = 1;
}
for (int i = 1; i < n; ++i){
int x = read(), y = read();
addedge(x, y); addedge(y, x);
}
dfs(1, 0);
printf("%lld\n", ans);
return 0;
}