题目链接:
解题思路:
现递归枚举每个连通块中是否有k个点,若存在k个点则将他置为0,且连通块为k个点的计数器++,最后只需要判断n / k == 计数器即可
#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int N = 100010, M = 2 * N; int cnt; int n, k; int st[N]; int h[N], e[M], ne[M], idx; void add(int a, int b) { e[idx] = b; ne[idx] = h[a]; h[a] = idx; idx ++ ; } void dfs(int u, int fa) { st[u] = 1; for (int i = h[u]; i != -1; i = ne[i]) { int j = e[i]; if (j != fa) { dfs(j, u); st[u] += st[j]; } } if (st[u] == k) { st[u] = 0; cnt ++ ; } } int main() { int T; cin >> T; while (T -- ) { cin >> n >> k; idx = 0; memset(h, -1, sizeof h); for (int i = 0; i < n - 1; i ++ ) { int a, b; scanf("%d %d", &a, &b); add(a, b), add(b, a); } if (n % k != 0) //说明无解 { puts("NO"); continue; } memset(st, 0, sizeof st); cnt = 0; dfs(1, -1); if (n / k == cnt) puts("YES"); else puts("NO"); } return 0; }