多校签到题,dfs一下就好了。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 6 const int N = 101; 7 int head[N]; 8 int sum[N]; 9 bool f[N]; 10 int n, k, e; 11 12 struct Edge 13 { 14 int v, next; 15 } edge[N]; 16 17 void addEdge( int u, int v ) 18 { 19 edge[e].v = v; 20 edge[e].next = head[u]; 21 head[u] = e++; 22 } 23 24 void dfs( int u ) 25 { 26 sum[u] = 1; 27 for ( int i = head[u]; i != -1; i = edge[i].next ) 28 { 29 int v = edge[i].v; 30 dfs(v); 31 sum[u] += sum[v]; 32 } 33 } 34 35 int main() 36 { 37 while ( scanf("%d%d", &n, &k) != EOF ) 38 { 39 e = 0; 40 memset( head, -1, sizeof(head) ); 41 memset( f, 0, sizeof(f) ); 42 for ( int i = 1; i < n; i++ ) 43 { 44 int u, v; 45 scanf("%d%d", &u, &v); 46 addEdge( u, v ); 47 f[v] = 1; 48 } 49 int root; 50 for ( int i = 1; i <= n; i++ ) 51 { 52 if ( !f[i] ) 53 { 54 root = i; 55 break; 56 } 57 } 58 dfs(root); 59 int cnt = 0; 60 for ( int i = 1; i <= n; i++ ) 61 { 62 if ( sum[i] == k + 1 ) 63 { 64 cnt++; 65 } 66 } 67 printf("%d ", cnt); 68 } 69 return 0; 70 }