Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define F first
- #define S second
- #define all(x) x.begin(),x.end()
- #define endl '\n'
- using namespace std;
- using ll = long long;
- using pii = pair<int, int>;
- const int INF = 0x3f3f3f3f;
- const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
- const int MOD = 1000000007;
- const int MAXN = 200010;
- vector<int> adj[MAXN];
- ll down[MAXN], up[MAXN], sz[MAXN];
- void dfs1(int u, int p){
- sz[u] = 1;
- down[u] = 0;
- for(int to: adj[u]){
- if(to == p) continue;
- dfs1(to, u);
- sz[u] += sz[to];
- down[u] += (down[to] + sz[to]);
- }
- }
- int n;
- void dfs2(int u, int p){
- for(int to: adj[u]){
- if(to == p) continue;
- ll aux = down[u] - (sz[to] + down[to]) + up[u];
- up[to] = (aux + n-sz[to]);
- dfs2(to, u);
- }
- }
- int main() {
- ios_base::sync_with_stdio(false); cin.tie(NULL);
- cin >> n;
- for(int i=0; i<n-1; i++){
- int a, b;
- cin >> a >> b;
- adj[a].push_back(b);
- adj[b].push_back(a);
- }
- dfs1(1, 0);
- dfs2(1, 0);
- for(int i=1; i<=n; i++)
- cout << (down[i] + up[i]) << " ";
- cout << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement