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
| #include "iostream" #include "algorithm" #include "cstring" #include "cstdio" #include "vector" #include "queue" using namespace std; #define MAXN 1000006 int n , k; int G[MAXN][26] , st[MAXN] , dfn[MAXN] , bac[MAXN] , R[MAXN] , S[MAXN] , clo = 0; int id[MAXN << 2] , cnt; int head[MAXN * 5] , to[MAXN << 3] , nex[MAXN << 3] , wto[MAXN << 3] , ecn; void ade( int u , int v , int w ) { to[++ ecn] = v , nex[ecn] = head[u] , head[u] = ecn , wto[ecn] = w; } void dfs( int u , int fa ) { dfn[u] = clo + 1; if( st[u] ) bac[++ clo] = u , dfn[u] = clo; for( int i = 0 ; i < 26 ; ++ i ) if( G[u][i] ) ade( u , G[u][i] , 1 ) , dfs( G[u][i] , u ); R[u] = clo; } void build( int rt , int l , int r ) { id[rt] = ++ cnt; if( l == r ) { id[rt] = bac[l]; return; } int m = l + r >> 1; build( rt << 1 , l , m ) , build( rt << 1 | 1 , m + 1 , r ); ade( id[rt] , id[rt << 1] , 0) , ade( id[rt] , id[rt << 1 | 1] , m - l + 1 ); } void Ade( int rt , int l , int r , int L , int R , int x ) { if( L <= l && R >= r ) { ade( x , id[rt] , l - L + 1 ); return; } int m = l + r >> 1; if( L <= m ) Ade( rt << 1 , l , m , L , R , x ); if( R > m ) Ade( rt << 1 | 1 , m + 1 , r , L , R , x ); } #define pii pair<int,int> priority_queue<pii> Q; int dis[MAXN * 5] , vis[MAXN * 5]; void dijk( int s ) { memset( dis , 0x3f , sizeof dis ) , dis[s] = 0; Q.push( make_pair( 0 , s ) ); while( !Q.empty( ) ) { int x = Q.top().second; Q.pop(); if( vis[x] ) continue; vis[x] = 1; for( int i = head[x] ; i ; i = nex[i] ) { int v = to[i]; if( dis[v] > dis[x] + wto[i] && !vis[v] ) Q.push( make_pair( - ( dis[v] = dis[x] + wto[i] ) , v ) ); } } } int fa[MAXN]; int main() { cin >> n; char ch[3]; for( int i = 1 , p ; i <= n ; ++ i ) { scanf("%d%s",&p,ch); G[p][ch[0] - 'a'] = i , fa[i] = p; } cin >> k; for( int i = 1 , u ; i <= k ; ++ i ) scanf("%d",&S[i]) , st[S[i]] = 1; cnt = n; dfs( 0 , 0 ); build( 1 , 1 , k ); for( int i = 0 ; i <= n ; ++ i ) if( dfn[i] <= R[i] && ( !i || dfn[i] != dfn[fa[i]] || R[i] != R[fa[i]] ) ) Ade( 1 , 1 , k , dfn[i] , R[i] , i ); dijk( 0 ); for( int i = 1 ; i <= k ; ++ i ) printf("%d%c",dis[S[i]]," \n"[i == k]); }
|