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>
using namespace std;
const int N = 1e6;
int n;
int sz[N];
vector<int> adj[N];
long long rans[N];
vector<int> xp[N];
int dans[N];
int lp[N];
bool valid[N];
int dfs(int v, int p) {
sz[v] = 1; lp[v] = 0;
for (int w : adj[v]) if (w != p) {
sz[v] += dfs(w,v);
lp[v] = max(lp[v], lp[w]+1);
}
return sz[v];
}
void dfsr(int v, int p, int len) {
rans[v] = v ? rans[p] + (n - sz[v]) - sz[v] : 0;
if (!v)
for (int i = 1; i < n; i++)
rans[v] += sz[i];
xp[v].push_back(len+1);
int max_sz = 0, llen = 0;
for (int w : adj[v]) if (w != p) {
if (sz[w] > max_sz) {
max_sz = sz[w];
llen = lp[w]+1;
}
xp[v].push_back(lp[w]+2);
sort(begin(xp[v]),end(xp[v]),greater<int>());
while (xp[v].size() > 2) xp[v].pop_back();
}
if (n-sz[v] > max_sz) {
max_sz = n-sz[v];
llen = len;
}
valid[v] = max_sz - (n - 1 - max_sz) <= 1;
dans[v] = max(len, lp[v]);
if (max_sz - (n - 1 - max_sz) == 1)
dans[v] = llen;
for (int w : adj[v]) if (w != p) {
int l = xp[v][0];
if (xp[v][0] == lp[w]+2) l = xp[v][1];
dfsr(w,v,l);
}
}
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);
}
dfs(0,-1);
dfsr(0,-1, 0);
stringstream ss;
for (int i = 0; i < n; i++)
ss << (valid[i] ? 2*rans[i]-dans[i] : -1) << endl;
cout << ss.str();
return 0;
}
# | 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... |
# | 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... |