This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define mp make_pair
using namespace std;
void db() {cout << endl;}
template <typename T, typename ...U> void db(T a, U ...b) {
//return;
cout << a << ' ', db(b...);
}
#ifdef Cloud
#define file freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout)
#else
#define file ios::sync_with_stdio(false); cin.tie(0)
#endif
const int N = 3001, inf = 1e9 + 1;
void solve(){
int n;
cin >> n;
int c[n + 1];
vector<int> g[n + 1];
for (int i = 0; i < n - 1; i++){
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
for (int i = 1; i <= n; i++) cin >> c[i];
auto solve2 = [&](int _c){
queue<int> q;
int dis[n + 1]{}, vis[n + 1]{}, mi[n + 1], par[n + 1]{};
for (int &i : mi) i = inf;
for (int i = 1; i <= n; i++) if (c[i] == _c) {
vis[i] = 1;
par[i] = i;
q.push(i);
}
while (!q.empty()){
int u = q.front();
q.pop();
for (int i : g[u]){
if (par[i] == par[u]) continue;
if (vis[i]){
mi[par[u]] = min(mi[par[u]], dis[u] + dis[i] + 1);
mi[par[i]] = min(mi[par[i]], dis[u] + dis[i] + 1);
}
else{
dis[i] = dis[u] + 1;
vis[i] = 1;
par[i] = u;
q.push(i);
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) if (par[i] == i) ans = max(ans, mi[i]);
return ans;
};
int ans = max(solve2(0), solve2(1));
if (ans >= n) return void(cout << -1 << '\n');
cout << ans << '\n';
for (int i = 1; i <= n; i++) cout << c[i] << ' ';
cout << '\n';
}
signed main(){
file;
int t;
cin >> t;
while (t--)
solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |