bzoj 1776

时间:2023-03-09 15:51:12
bzoj 1776

收获:

树上直径一定包含深度最深的点。

然后O(nlogn) 暴力。

 /**************************************************************
Problem: 1776
User: idy002
Language: C++
Result: Accepted
Time:2064 ms
Memory:31756 kb
****************************************************************/ #include <cstdio>
#include <vector>
#define maxn 200010
#define maxp 18
using namespace std; int n, m, root;
int anc[maxn][maxp+], dep[maxn];
vector<int> g[maxn];
vector<int> grp[maxn]; void dfs( int u ) {
for( int p=; p<=maxp; p++ )
anc[u][p]=anc[anc[u][p-]][p-];
for( int t=; t<g[u].size(); t++ ) {
int v=g[u][t];
anc[v][] = u;
dep[v] = dep[u]+;
dfs( v );
}
}
int lca( int u, int v ) {
if( dep[u]<dep[v] ) swap(u,v);
int t=dep[u]-dep[v];
for( int p=; t; t>>=,p++ )
if( t& ) u=anc[u][p];
if( u==v ) return u;
for( int p=maxp; anc[u][]!=anc[v][]; p-- )
if( anc[u][p]!=anc[v][p] )
u=anc[u][p],v=anc[v][p];
return anc[u][];
}
int main() {
scanf( "%d%d", &n, &m );
for( int i=,a,b; i<=n; i++ ) {
scanf( "%d%d", &a, &b );
grp[a].push_back( i );
if( b== ) root=i;
else g[b].push_back( i );
}
dep[root] = ;
anc[root][] = root;
dfs(root);
for( int i=; i<=m; i++ ) {
int md = grp[i][];
for( int t=; t<grp[i].size(); t++ )
if( dep[grp[i][t]]>dep[md] )
md=grp[i][t];
int u=md;
int ans=;
for( int t=; t<grp[i].size(); t++ ) {
int v=grp[i][t];
int ca=lca(u,v);
int dis = dep[u]+dep[v]-dep[ca]-dep[ca];
if( ans<dis ) ans=dis;
}
printf( "%d\n", ans );
}
}