标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1788 Accepted Submission(s): 863
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 using namespace std; 5 6 struct node 7 { 8 int next, to; 9 int step; 10 } a[100005]; 11 12 int head[100005]; 13 int n, d, len, ans; 14 15 void Add(int x, int y) 16 { 17 a[len].to = y; 18 a[len].next = head[x]; 19 head[x] = len++; 20 } 21 22 void Dfs(int x, int step) 23 { 24 int i, j, k; 25 if(head[x] == -1) 26 return; 27 for(i = head[x]; i!=-1; i = a[i].next) 28 { 29 k = a[i].to; 30 a[i].step = step+1; //这里的step和结构体里边的不一样; 31 if(a[i].step>d) 32 ans++; 33 Dfs(k,a[i].step); //结构体已经清零。 34 } 35 36 } 37 38 int main() 39 { 40 int t, i, j, x, y; 41 while(~scanf("%d", &t)) 42 { 43 while(t--) 44 { 45 memset(head, -1, sizeof(head)); 46 memset(a, 0, sizeof(a)); 47 scanf("%d %d", &n, &d); 48 len = 0; 49 for(i=1; i<n; i++) 50 { 51 scanf("%d %d", &x, &y); 52 Add(x, y); 53 } 54 ans = 0; 55 Dfs(0, 0); 56 printf("%d\n", ans); 57 } 58 } 59 return 0; 60 }
1 #include <vector> 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 int dis[100005]; vector<int>v[100005]; 8 void Dfs(int x) 9 { 10 for(int i = 0; i < v[x].size(); i++) 11 { 12 dis[v[x][i]] = dis[x] + 1; 13 Dfs(v[x][i]); 14 } 15 return; 16 } 17 int main() 18 { 19 int t; 20 scanf("%d", &t); 21 while(t--) 22 { 23 int n, m, x, y; 24 scanf("%d %d", &n, &m); 25 for(int i=1; i < n; i++) 26 v[i].clear(); 27 for(int i=1; i<n; i++) 28 { 29 scanf("%d %d", &x, &y); 30 v[x].push_back(y); 31 } 32 memset(dis, 0, sizeof(dis)); //数组清0, 保存路径经过结点个数; 33 Dfs(0); 34 int ans = 0; 35 for(int i=1; i<n; i++) 36 { 37 if(dis[i] > m) 38 ans++; 39 } 40 printf("%d\n", ans); 41 } 42 return 0; 43 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4707546.html