321C - Ciel the Commander - CodeForces Solution


constructive algorithms dfs and similar divide and conquer greedy trees *2100

Please click on ads to support us..

C++ Code:

/*
*  In the name of God
*
*  Author: Farbod Doost
*  Last Modified: Thu, 09 Mar 2023 (04:29:26)
*
*/
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 5;

int n;
vector <int> adj[N];

bool vis[N];
int dp[N], b[N];

void dfs(int v, int p)
{
    dp[v] = 1;
    for (auto u: adj[v])
        if (u != p && !vis[u])
            dfs(u, v), dp[v] += dp[u];
    return;
}

int get(int v, int p, int sz)
{
    for (auto u: adj[v]) {
        if (u == p || vis[u])
            continue;
        if (dp[u] > sz / 2)
            return get(u, v, sz);
    }
    return v;
}

void cent(int v = 0, int p = -1)
{
    dfs(v, -1);
    v = get(v, -1, dp[v]);

    vis[v] = 1;
    if (p == -1)
        b[v] = 0;
    else
        b[v] = b[p] + 1;

    for (auto u: adj[v])
        if (!vis[u])
            cent(u, v);

    return;
}

signed main()
{
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);

    cin >> n;
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v, u--, v--;

        adj[u].push_back(v),
        adj[v].push_back(u);
    }

    cent();

    for (int i = 0; i < n; i++)
        cout << char('A' + b[i]) << ' ';

    return 0;
}


Comments

Submit
0 Comments
More Questions

1366C - Palindromic Paths
336A - Vasily the Bear and Triangle
926A - 2-3-numbers
276D - Little Girl and Maximum XOR
1253C - Sweets Eating
1047A - Little C Loves 3 I
758D - Ability To Convert
733A - Grasshopper And the String
216A - Tiling with Hexagons
1351B - Square
1225A - Forgetting Things
1717A - Madoka and Strange Thoughts
1717B - Madoka and Underground Competitions
61B - Hard Work
959B - Mahmoud and Ehab and the message
802G - Fake News (easy)
1717C - Madoka and Formal Statement
420A - Start Up
1031A - Golden Plate
1559C - Mocha and Hiking
427B - Prison Transfer
330A - Cakeminator
426A - Sereja and Mugs
363A - Soroban
1585C - Minimize Distance
1506E - Restoring the Permutation
1539A - Contest Start
363D - Renting Bikes
1198D - Rectangle Painting 1
1023B - Pair of Toys