fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5. const int MAXN = 300000;
  6.  
  7. vector<int> adj[MAXN+1];
  8. vector<int> depths[MAXN+1];
  9. int maxd;
  10.  
  11. void dfs(int u, int p, int d) {
  12. // record node u at depth d
  13. depths[d].push_back(u);
  14. maxd = max(maxd, d);
  15. // recurse on children
  16. for (int v : adj[u]) {
  17. if (v == p) continue;
  18. dfs(v, u, d+1);
  19. }
  20. }
  21.  
  22. int main(){
  23. ios::sync_with_stdio(false);
  24. cin.tie(nullptr);
  25.  
  26. int T;
  27. cin >> T;
  28. while (T--) {
  29. int n;
  30. cin >> n;
  31. // clear adjacency & depths
  32. for (int i = 1; i <= n; i++) {
  33. adj[i].clear();
  34. depths[i].clear();
  35. }
  36. maxd = 0;
  37.  
  38. // read the tree
  39. for (int i = 0; i < n-1; i++) {
  40. int a, b;
  41. cin >> a >> b;
  42. adj[a].push_back(b);
  43. adj[b].push_back(a);
  44. }
  45.  
  46. // bucket nodes by depth starting from node 1
  47. dfs(1, 0, 0);
  48.  
  49. // dp[d] = number of ways to choose one node in each depth ≤ d
  50. vector<ll> dp(maxd+1);
  51. dp[0] = 1;
  52. for (int d = 1; d <= maxd; d++) {
  53. ll cnt = depths[d].size();
  54. dp[d] = cnt * dp[d-1];
  55. }
  56.  
  57. // sum up dp[0] + dp[1] + ... + dp[maxd]
  58. ll res = 0;
  59. for (int d = 0; d <= maxd; d++) {
  60. res += dp[d];
  61. }
  62.  
  63. cout << res << "\n";
  64. }
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0.01s 17656KB
stdin
3
4
1 2 1
3
1 2
7
1 2 2 1 4 5
stdout
4
3
1