D. Vertical Paths
# include <iostream>
# include <cstring>
# include <algorithm>
# include <cmath>
# include <vector>
# include <map>
# include <set>
# include <functional>
using namespace std;
const int N = 200010 ;
void solve ( )
{
int n; cin>> n;
vector< int > p ( n) ;
vector< bool > is_leaf ( n, true ) ;
for ( int i= 0 ; i< n; i++ )
{
cin>> p[ i] ; p[ i] -- ;
if ( p[ i] != i) is_leaf[ p[ i] ] = false ;
}
cout<< count ( is_leaf. begin ( ) , is_leaf. end ( ) , true ) << '\n' ;
vector< bool > vis ( n) ;
for ( int i= 0 ; i< n; i++ )
{
if ( is_leaf[ i] )
{
vector< int > vec;
for ( int j= i; ! vis[ j] ; j= p[ j] )
{
vis[ j] = true ;
vec. push_back ( j) ;
}
reverse ( vec. begin ( ) , vec. end ( ) ) ;
cout<< vec. size ( ) << '\n' ;
for ( auto x : vec) cout<< x+ 1 << ' ' ;
cout<< '\n' ;
}
}
cout<< '\n' ;
}
signed main ( )
{
int T; cin>> T;
while ( T-- ) solve ( ) ;
}
E. Replace With the Previous, Minimize
# include <iostream>
# include <cstring>
# include <algorithm>
using namespace std;
const int N = 200010 ;
void solve ( )
{
int n, k; cin>> n>> k;
string s; cin>> s;
int maxv= 0 ;
for ( int i= 0 ; i< n; i++ )
{
if ( s[ i] - 'a' > k)
{
char l= s[ i] - ( k- maxv) ;
char r= s[ i] ;
for ( int j= 0 ; j< n; j++ )
{
if ( s[ j] >= l&& s[ j] <= r)
{
s[ j] = l;
}
}
break ;
}
maxv= max ( maxv, s[ i] - 'a' ) ;
}
for ( int i= 0 ; i< n; i++ ) if ( s[ i] - 'a' <= maxv) s[ i] = 'a' ;
cout<< s<< '\n' ;
}
signed main ( )
{
int T; cin>> T;
while ( T-- ) solve ( ) ;
}
F. Vlad and Unfinished Business
# include <iostream>
# include <cstring>
# include <algorithm>
# include <vector>
# include <functional>
using namespace std;
const int N = 200010 ;
int n, k, x, y;
void solve ( )
{
cin>> n>> k>> x>> y;
vector< int > a, p ( n+ 1 ) , depth ( n+ 1 ) ;
vector< vector< int >> g ( n+ 1 ) ;
vector< bool > vis ( n+ 1 ) ;
for ( int i= 0 , x; i< k; i++ ) cin>> x, a. push_back ( x) ;
a. push_back ( y) ;
for ( int i= 1 , u, v; i< n; i++ )
{
cin>> u>> v;
g[ u] . push_back ( v) ;
g[ v] . push_back ( u) ;
}
function< void ( int , int ) > dfs = [ & ] ( int u, int fa)
{
for ( auto v : g[ u] )
{
if ( v== fa) continue ;
p[ v] = u;
depth[ v] = depth[ u] + 1 ;
dfs ( v, u) ;
}
} ;
dfs ( x, 0 ) ;
int res= 0 ;
vis[ x] = true ;
for ( auto u : a)
{
while ( ! vis[ u] )
{
vis[ u] = true ;
res+= 2 ;
u= p[ u] ;
}
}
res-= depth[ y] ;
cout<< res<< '\n' ;
}
signed main ( )
{
int T; cin>> T;
while ( T-- ) solve ( ) ;
}
G. Sorting Pancakes