跳到正文

woshnd

1040231

人生到处知何似,应似飞鸿踏雪泥

这是 2026年11月5日 存档的第 5 版,不是当前版本。查看当前版本

资料、奖项与版本

资料

编号
1040231
抓取

奖项

2026 NOI 女生竞赛
三等奖
2025 CSP-S
二等奖
2025 NOIP
二等奖
2024 CSP-J
一等奖
2024 CSP-S
二等奖
2023 CSP-J
一等奖

版本

  1. v9当前
  2. v8
  3. v7
  4. v6
更早的 5 个版本
  1. v5
  2. v4
  3. v3
  4. v2
  5. v1

300道题纪念 2025.9.24 21:53

350道题纪念 2025.11.7 22:30

400道题纪念 2025.11.28 20:27

450道题纪念 2026.1.23 18:51

500道题纪念 2026.2.4 12:51

550道题纪念 2026.5.4 16:51

600道题纪念 2026.8.14 19:23

650道题纪念 2026.8.29 15:36

700道题预告 2026.11.2 11:57

C++
#include <bits/stdc++.h>
#define ll long long
#define inl inline
using namespace std;

inl int read() {
	int s = 0;
	char ch = getchar();
	while (ch < '0' || ch > '9')
		ch = getchar();
	while (ch <= '9' && ch >= '0')
		s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
	return s;
}
const int N = 100005;
int n, k, ans, fa[N], sz[N], son[N], del[N];
vector<int> e[N];

void dfs1(int x) {
	sz[x] = 1, son[x] = 0;
	for (int i = 0, szz = e[x].size(); i < szz; ++i) {
		int y = e[x][i];
		if (y == fa[x])
			continue;
		fa[y] = x;
		dfs1(y);
		if (sz[y] >= k)
			++son[x];
		sz[x] += sz[y];
	}
}

void dfs2(int x) {
	del[x] = 0;
	int mx = -0x3f3f3f3f, mxx = -0x3f3f3f3f;
	for (int i = 0, szz = e[x].size(); i < szz; ++i) {
		int y = e[x][i];
		if (y == fa[x])
			continue;
		dfs2(y);
		if (max(del[y], son[y]) - (sz[y] >= k) > mx)
			mxx = mx, mx = max(del[y], son[y]) - (sz[y] >= k);
		else if (max(del[y], son[y]) - (sz[y] >= k) > mxx)
			mxx = max(del[y], son[y]) - (sz[y] >= k);
		del[x] = max(del[x], son[x] - (sz[y] >= k) + max(del[y], son[y]));
	}
	if (sz[x] > 1)
		ans = max(ans, del[x] + (sz[1] - sz[x] >= k));
	ans = max(ans, son[x] + mx + mxx + (sz[1] - sz[x] >= k));
}

void run() {
	n = read(), k = read();
	for (int i = 1; i <= n; ++i)
		e[i].clear(), fa[i] = 0;
	for (int i = 1, x, y; i < n; ++i) {
		x = read(), y = read();
		e[x].push_back(y), e[y].push_back(x);
	}
	dfs1(1);
	ans = 0;
	dfs2(1);
	printf("%d\n", ans);
}

int main() {
	freopen("tree.in", "r", stdin);
	freopen("tree.out", "w", stdout);
	int t;
	scanf("%d", &t);
	for (; t; --t)
		run();
	return 0;
}