这个题目是个递推,不过由于是树形的,需要dfs来完成递推的过程。
关键在于p[now] += p[to]+1;如果now能manage to的话。
此处采用链式前向星来保存关系图。
代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <set> #include <map> #include <queue> #include <string> #include <algorithm> #define LL long long using namespace std; const int maxN = 105; struct Edge { int to, next; }edge[maxN]; int head[maxN], cnt; void addEdge(int u, int v) { edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt; cnt++; } void initEdge() { memset(head, -1, sizeof(head)); cnt = 0; } int n, k; int fa[maxN], p[maxN]; void input() { initEdge(); memset(p, -1, sizeof(p)); int u, v; for (int i = 1; i < n; ++i) { scanf("%d%d", &u, &v); addEdge(u, v); } } void dfs(int now) { p[now] = 0; int to; for (int i = head[now]; i != -1; i = edge[i].next) { to = edge[i].to; if (p[to] == -1) dfs(to); p[now] += p[to]+1; } } void work() { int ans = 0; for (int i = 1; i <= n; ++i) { if (p[i] != -1) { if (p[i] == k) ans++; } else { dfs(i); if (p[i] == k) ans++; } } printf("%d\n", ans); } int main() { //freopen("test.in", "r", stdin); while (scanf("%d%d", &n, &k) != EOF) { input(); work(); } return 0; }