Submission #497023

#TimeUsernameProblemLanguageResultExecution timeMemory
497023abc864197532Balanced Tree (info1cup18_balancedtree)C++17
0 / 100
211 ms61044 KiB
#include <bits/stdc++.h> using namespace std; #define lli long long int #define mp make_pair #define eb emplace_back #define pb push_back #define X first #define Y second #define pii pair<int,int> #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() void abc() {cout << endl;} template <typename T, typename ...U> void abc(T i, U ...j) { cout << i << ' ', abc(j...); } template <typename T> void printv(T l, T r) { for (; l != r; ++l) cout << *l << " \n"[l + 1 == r]; } #ifdef Doludu #define test(x...) abc("[" + string(#x) + "]", x); #else #define test(x...) void(0); #endif const int N = 100000; int main () { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector <vector <int>> adj(n); for (int i = 0, u, v; i < n - 1; ++i) { cin >> u >> v, --u, --v; adj[u].pb(v), adj[v].pb(u); } vector <int> a(n); for (int i = 0; i < n; ++i) cin >> a[i], assert(a[i] != -1); if (count(all(a), 0) == 1 || count(all(a), 1) == 1) { cout << -1 << endl; continue; } vector <vector <int>> dp1(n, vector <int>(2, 1 << 30)); vector <vector <int>> dp2(n, vector <int>(2, 1 << 30)); vector <vector <int>> dp3(n, vector <int>(2, 1 << 30)); vector <int> dep(n, 0); auto upd = [&](int i, int j, int v) { if (dp1[i][j] >= v) dp2[i][j] = dp1[i][j], dp1[i][j] = v; else if (dp2[i][j] >= v) dp2[i][j] = v; }; function<void(int, int)> dfs = [&](int v, int pa) { for (int u : adj[v]) if (u != pa) { dep[u] = dep[v] + 1; dfs(u, v); upd(v, 0, dp1[u][0] + 1); upd(v, 0, dp2[u][0] + 1); upd(v, 1, dp1[u][1] + 1); upd(v, 1, dp2[u][1] + 1); upd(v, a[u], 1); } }; function<void(int, int)> dfs2 = [&](int v, int pa) { if (~pa) { dp3[v][t] = dp3[pa][t] + 1; for (int t : {0, 1}) { if (dp1[pa][t] == dp1[v][t]) { // from v dp3[v][t] = min(dp3[v][t], dp2[pa][t] + 1); } else { // not from v dp3[v][t] = min(dp3[v][t], dp1[pa][t] + 1); } } } for (int u : adj[v]) if (u != pa) { dfs2(u, v); } }; dfs(0, -1); dfs2(0, -1); int ans = 0; for (int i = 0; i < n; ++i) { ans = max(ans, min(dp1[i][a[i]], dp3[i][a[i]])); } cout << ans << endl; printv(all(a)); } }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...