求助!在线等!急!!
查看原帖
求助!在线等!急!!
107468
hulean楼主2020/8/1 13:30

全 WA 。

估计是犯了什么zz错误,求大佬指点!!

#include <bits/stdc++.h>
using namespace std ;
const int MAXN = 3e5 + 5 ;
int deep[ MAXN ] ;
int fa[ MAXN ][ 20 ] ;
int n , a[ MAXN ] , d[ MAXN ] ;
struct Node {
    int next , to ;
} edge[ MAXN << 1 ] ;
int head[ MAXN ] , cnt ;
inline int read () {
    int tot = 0 , f = 1 ; char c = getchar () ;
    while ( c < '0' || c > '9' ) { if ( c == '-' ) f = -1 ; c = getchar () ; }
    while ( c >= '0' && c <= '9' ) { tot = tot * 10 + c - '0' ; c = getchar () ; }
    return tot * f ;
}
inline void add ( int x , int y ) {
    edge[ ++ cnt ].next = head[ x ] ;
    edge[ cnt ].to = y ;
    head[ x ] = cnt ;
}
inline void dfs ( int u , int father ) {
    deep[ u ] = deep[ father ] + 1 ;
    fa[ u ][ 0 ] = father ;
    for ( int i = 1 ; i <= 19 ; i ++ )
        fa[ u ][ i ] = fa[ fa[ u ][ i - 1 ] ][ i - 1 ] ;
    for ( int i = head[ u ] ; i ; i = edge[ i ].next ) {
        int v = edge[ i ].to ;
        if ( v == father ) continue ;
        dfs ( v , u ) ;
    }
}
inline int Lca ( int x , int y ) {
    if ( x == y ) return x ;
    if ( deep[ x ] < deep[ y ] ) swap ( x , y ) ;
    for ( int i = 19 ; i >= 0 ; i -- ) {
        if ( fa[ x ][ i ] >= y ) x = fa[ x ][ i ] ;
    }
    if ( x == y ) return x ;
    for ( int i = 19 ; i >= 0 ; i -- ) {
        if ( fa[ x ][ i ] != fa[ y ][ i ] )
            x = fa[ x ][ i ] , y = fa[ y ][ i ] ;
    }
    return fa[ x ][ 0 ] ;
}
inline void solve ( int u , int father ) {
    for ( int i = head[ u ] ; i ; i = edge[ i ].next ) {
        int v = edge[ i ].to ;
        if ( v == father ) continue ;
        solve ( v , u ) ;
        d[ u ] += d[ v ] ;
    }
}
signed main () {
    n = read () ;
    for ( int i = 1 ; i <= n ; i ++ ) a[ i ] = read () ;
    for ( int i = 1 ; i < n ; i ++ ) {
        int x = read () , y = read () ;
        add ( x , y ) ; add ( y , x ) ;
    }
    dfs ( 1 , 0 ) ;
    // for ( int i = 1 ; i <= n ; i ++ ) cout << fa[ i ][ 1 ] << " " ; cout << endl ;
    for ( int i = 2 ; i <= n ; i ++ ) {
        int lca = Lca ( a[ i ] , a[ i - 1 ] ) ;
        // cout << a[ i ] << " " << a[ i - 1 ] << " " << lca << endl ;
        d[ a[ i - 1 ] ] ++ ; d[ a[ i ] ] ++ ;
        d[ lca ] -- ; d[ fa[ lca ][ 0 ] ] -- ;
    }
    /*for ( int i = 1 ; i <= n ; i ++ )
        cout << d[ i ] << " " ; cout << endl ;*/
    solve ( 1 , 0 ) ;
    for ( int i = 2 ; i <= n ; i ++ )
        d[ a[ i ] ] -- ;
    for ( int i = 1 ; i <= n ; i ++ )
        printf ( "%d\n" , d[ i ] ) ;
    printf ( "\n" ) ;
    return 0 ;
}

2020/8/1 13:30
加载中...