1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| const int maxn = 1e6 + 5;
vector<int> adj[maxn]; int dep[maxn], fa[maxn], ed;
void dfs1( int u, int p ) { fa[u] = p; dep[u] = dep[p] + 1; if( ed == 0 || dep[u] > dep[ed] ) ed = u;
for( int v : adj[u] ) { if( v != p ) dfs1( v, u ); } }
int mxdep;
void dfs2( int u, int p, int d ) { dep[u] = d; mxdep = max( mxdep, d );
for( int v : adj[u] ) { if( v != p ) dfs2( v, u, d + 1 ); } }
bool dfs3( int u, int p, vector<int> &vec ) { int cnt = 0; for( int v : adj[u] ) { if( v == p ) continue; if( dfs3( v, u, vec ) ) ++ cnt; }
bool ok = ( dep[u] == mxdep || cnt > 0 ); if( ok && cnt != 1 ) vec.push_back( dep[u] ); return ok; }
vector<int> calc( int rt, int ban ) { vector<int> res;
mxdep = 0; dfs2( rt, ban, 0 ); dfs3( rt, ban, res );
sort( res.begin( ), res.end( ) ); res.erase( unique( res.begin( ), res.end( ) ), res.end( ) ); return res; }
void solve( ) { int n; cin >> n;
for( int i = 1; i <= n; ++ i ) adj[i].clear( );
for( int i = 1; i < n; ++ i ) { int u, v; cin >> u >> v; adj[u].push_back( v ); adj[v].push_back( u ); }
ed = 0; dfs1( 1, 0 ); int s = ed; ed = 0; dfs1( s, 0 ); int t = ed;
vector<int> path; for( int x = t; ; x = fa[x] ) { path.push_back( x ); if( x == s ) break; } reverse( path.begin( ), path.end( ) );
int d = ( (int)path.size( ) - 1 ) / 2; int a = path[d], b = path[d + 1];
vector<int> A = calc( a, b ); vector<int> B = calc( b, a );
set<int> ans; for( int x : A ) { for( int y : B ) ans.insert( x + y + 1 ); }
cout << ans.size( ); for( int x : ans ) cout << ' ' << x; cout << '\n'; }
|