Last active
February 4, 2023 10:01
-
-
Save ankitjosh78/68656c21e639575e1af816fa6bb7b77d to your computer and use it in GitHub Desktop.
hangingTree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "bits/stdc++.h" | |
using namespace std; | |
#define endl '\n' | |
#define mp make_pair | |
#define int long long | |
#define pb push_back | |
#define vi vector<int> | |
#define vvi vector<vector<int>> | |
#define ar array | |
#define ll long long | |
#define ld long double | |
#define sza(x) ((int)x.size()) | |
#define all(a) (a).begin(), (a).end() | |
const int max_n = 1e6 + 5; | |
const ll mod = 1e9 + 7; | |
const ll M = 1e9; | |
const ll inf = 1e9; | |
const ld eps = 1e-9; | |
void setio(string name = "") { | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
if (!name.empty()) { | |
freopen((name + ".txt").c_str(), "r", stdin); | |
freopen((name + ".out").c_str(), "w", stdout); | |
} else { | |
#ifndef ONLINE_JUDGE | |
freopen("input.txt", "r", stdin); | |
freopen("output.txt", "w", stdout); | |
#endif | |
} | |
} | |
int dx[8] = {1, -1, 0, 0, 1, 1, -1, -1}; | |
int dy[8] = {0, 0, 1, -1, 1, -1, -1, 1}; | |
int hdx[] = {-1, -2, -2, -1, 1, 2, 2, 1}; | |
int hdy[] = {-2, -1, 1, 2, 2, 1, -1, -2}; | |
bool inside(int x, int y, int n, int m) { | |
return x >= 0 && x < n && y >= 0 && y < m; | |
} | |
vector<int> adj[max_n]; | |
vector<int> color(max_n); | |
vector<int> cnt(max_n); | |
set<int> s[max_n]; | |
void dfs(int u) { | |
s[u].insert(color[u]); | |
for (int v : adj[u]) { | |
dfs(v); | |
if (s[v].size() > s[u].size()) | |
swap(s[u], s[v]); | |
s[u].insert(s[v].begin(), s[v].end()); | |
s[v].clear(); | |
} | |
cnt[u] = s[u].size(); | |
} | |
void solve() { | |
int n; | |
cin >> n; | |
int root = -1; | |
for (int i = 1; i <= n; i++) { | |
int parent, col; | |
cin >> parent >> col; | |
color[i] = col; | |
if (parent == 0) { | |
root = i; | |
} else | |
adj[parent].push_back(i); | |
} | |
dfs(root); | |
for (int i = 1; i <= n; i++) { | |
cout << cnt[i] << " "; | |
} | |
cout << endl; | |
} | |
int32_t main() { | |
setio(); | |
int tc = 1; | |
auto start_time = clock(); | |
// cin >> tc; | |
for (int t = 1; t <= tc; t++) { | |
// cout << "case #" << t << ": "; | |
solve(); | |
} | |
auto end_time = clock(); | |
#ifndef ONLINE_JUDGE | |
cout << "Time taken:" << (double)(end_time - start_time) / CLOCKS_PER_SEC | |
<< "s" << endl; | |
#endif | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment