Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Subtree Size

#include <bits/stdc++.h>
using namespace std;

class Tree {
  public:
    int n, timer;
    vector<vector<int>> adj;
    vector<int> tin, tout;

    Tree(int n) {
        this->n = n;
        adj.resize(n);
        tin.resize(n);
        tout.resize(n);
        timer = 0;
    }

  public:
    void dfs(int src, int par) {
        tin[src] = ++timer;
        for (auto child : adj[src]) {
            if (child != par) {
                dfs(child, src);
            }
        }
        tout[src] = ++timer;
    }
};

void solve() {
    int n;
    cin >> n;
    Tree t(n);
    for (int i = 0; i < n - 1; i++) {
        int x, y;
        cin >> x >> y;
        x--;
        y--;
        t.adj[x].push_back(y);
        t.adj[y].push_back(x);
    }
    t.dfs(0, -1);

    for (int i = 0; i < n; i++) {
        cout << (t.tout[i] - t.tin[i] + 1) / 2 << " ";
    }
    cout << endl;
}

int main() {
    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        solve();
    }
    return 0;
}
#include <bits/stdc++.h>
using namespace std;

class Tree {
  public:
    int n, timer;
    vector<vector<int>> adj;
    vector<long long> a, dp;

    Tree(int n) {
        this->n = n;
        adj.resize(n);
        dp.resize(n);
        timer = 0;
    }

  public:
    void dfs(int src, int par) {
        dp[src] = 1;
        for (auto child : adj[src]) {
            if (child != par) {
                dfs(child, src);
                dp[src] += dp[child];
            }
        }
    }
};

void solve() {
    int n;
    cin >> n;
    Tree t(n);
    for (int i = 0; i < n - 1; i++) {
        int x, y;
        cin >> x >> y;
        x--;
        y--;
        t.adj[x].push_back(y);
        t.adj[y].push_back(x);
    }
    t.dfs(0, -1);

    for (int i = 0; i < n; i++) {
        cout << t.dp[i] << " ";
    }
    cout << endl;
}

int main() {
    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        solve();
    }
    return 0;
}