题目地址:点击打开链接
思路:刚开始思路就错,只记录了直接的下属,没想到下属的下属也属于老大管,深搜就可以解决,看到大神用并查集也A了,太叼了
AC代码1:
#include<iostream> #include<cstring> using namespace std; int a[110],visit[110],n; int dfs(int up) { int i,sum = 0; for(i=1; i<=n; i++) { if(a[i] == up) { sum++;//把小弟算进去 sum += dfs(i);//把小弟的小弟算进去 } } return sum; } int main() { int k,i,x,y,sum1; while(cin>>n>>k) { sum1 = 0; memset(a,0,sizeof(a)); for(i=0; i<n-1; i++) { cin>>x>>y; a[y] = x;//y的老大是x } for(i=1; i<=n; i++) { if(dfs(i) == k) sum1++; } cout<<sum1<<endl; } return 0; }
AC代码2:
#include<iostream> #include<cstring> using namespace std; int head[110],down[110]; void find(int x) { while(head[x] != x) { down[head[x]]++; x = head[x]; } } int main() { int n,k,i,sum1; int x,y; while(cin>>n>>k) { memset(down,0,sizeof(down)); sum1 = 0; for(i=1; i<=n; i++) { head[i] = i; } for(i=0; i<n-1; i++) { cin>>x>>y; head[y] = x; } for(i=1; i<=n; i++) { find(i); } for(i=1; i<=n; i++) { if(down[i] == k) sum1++; } cout<<sum1<<endl; } }
#include<iostream> #include<cstring> using namespace std; int map[110][110]; int n; int dfs(int head) { int i,sum = 0;//在这里初始化 for(i=1; i<=n; i++) { if(map[head][i]) { sum++; sum += dfs(i); } } return sum; } int main() { int k,i; int x,y,sum1; while(cin>>n>>k) { sum1 = 0; memset(map,0,sizeof(map)); for(i=0; i<n-1; i++) { cin>>x>>y; map[x][y] = 1; } for(i=1; i<=n; i++) { //sum = 0;不能在这里初始化sum,会导致一个值加多次 if(dfs(i) == k) sum1++; } cout<<sum1<<endl; } }大神地址: 点击打开链接