【题解】CF700B:Connecting Universities

原题传送门
直接贪心就好啦
对于某一条边,如果他的左边有 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值