이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#define rep(i,l,r) for(int i = (l); i < (r); i++)
#define per(i,r,l) for(int i = (r); i >= (l); i--)
#define all(x) begin(x), end(x)
#define sz(x) (int)size(x)
#define pb push_back
#define ff first
#define ss second
typedef long long ll;
typedef pair<int, int> pp;
void dbg(){
cerr << endl;
}
template<typename H, typename... T> void dbg(H h, T... t){
cerr << h << ", ";
dbg(t...);
}
void IOS(){
cin.tie(0) -> sync_with_stdio(0);
#ifndef ONLINE_JUDGE
// freopen("inp.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#define er(...) cerr << __LINE__ << " <" << #__VA_ARGS__ << ">: ", dbg(__VA_ARGS__)
#else
#define er(...) 0
#endif
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const ll mod = 1e9 + 7, mod2 = 1e9 + 9, maxn = 5e5 + 5, lg = 21, inf = ll(1e18) + 5, p = 9973;
ll pw(ll a, ll b){
if(b == 0) return 1;
ll k = pw(a, b>>1);
return k*k*(b&1ll?a:1);
}
vector<int> adj[maxn];
int cnt[maxn], par[maxn][lg], h[maxn];
void dfs(int r, int p){
cnt[r] = 1;
for(int c: adj[r]) if(c - p){
dfs(c, r);
cnt[r] += cnt[c];
}
}
vector<int> srt[maxn];
void dfs2(int r, int p){
cnt[r] = 1;
par[r][0] = p;
rep(i,1,lg) par[r][i] = par[par[r][i-1]][i-1];
for(int c: adj[r]) if(c - p){
h[c] = h[r] + 1;
dfs2(c, r);
cnt[r] += cnt[c];
}
srt[cnt[r]].pb(r);
}
int lca(int u, int v){
if(h[u] < h[v]) swap(u, v);
per(i,lg-1,0) if(h[par[u][i]] >= h[v]) u = par[u][i];
if(u == v) return u;
per(i,lg-1,0) if(par[u][i] - par[v][i]) u = par[u][i], v = par[v][i];
return par[u][0];
}
int dist(int u, int v){
return h[u] + h[v] - 2*h[lca(u, v)];
}
int getCen(int r, int p, int tot){
for(int c: adj[r]) if(c - p && cnt[c] + cnt[c] > tot) return getCen(c, r, tot);
return r;
}
int main(){ IOS();
int n; cin >> n;
rep(i,1,n){
int u, v; cin >> u >> v; u--, v--;
adj[u].pb(v), adj[v].pb(u);
}
dfs(0, -1);
int r = getCen(0, -1, n);
dfs2(r, r);
vector<int> ans(n + 1, 1);
int u = r, v = r, diam = 0;
for(int k = n>>1; k > 0; k--){
for(int x: srt[k]){
int d1 = dist(x, u), d2 = dist(x, v);
if(d1 > diam){
diam = d1, v = x;
} else if(d2 > diam){
diam = d2, u = x;
}
}
ans[k<<1] = diam + 1;
}
rep(i,1,n+1) cout << ans[i] << '\n';
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... |