多校第十场 1011 hdu 5416 CRB and Tree(树形dp)

#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#define MAX 100007

using namespace std;

typedef long long LL;
int t,n,q,s;
int dp[MAX];
vector<int> e[MAX];
vector<int> w[MAX];
LL mp[MAX*6];

void add ( int u , int v , int x )
{
    e[u].push_back ( v );
    e[v].push_back ( u );
    w[u].push_back ( x );
    w[v].push_back ( x );
}

void dfs ( int u , int p )
{
    if ( p == -1 ) dp[u] = 0;
    for ( int i = 0 ; i < e[u].size() ; i++ )
    {
        int v = e[u][i];
        int x = w[u][i];
        if ( v == p ) continue;
        dp[v] = dp[u]^x;
        dfs ( v , u );
    }
}

void init ( )
{
    for ( int i = 0 ; i < MAX ; i++ )
    {
        e[i].clear();
        w[i].clear();
    }
}

int main ( )
{
    scanf ( "%d" , &t );
    while ( t-- )
    {
        init ();
        scanf ("%d" , &n );
        int u,v,x;
        for ( int i = 1 ; i < n ; i++ )
        {
            scanf ("%d%d%d" , &u , &v , &x );
            add ( u , v , x );
        }
        dfs ( 1 , -1 );
        scanf ( "%d" , &q );
        while ( q-- )
        {
            scanf ( "%d" , &s );
            memset ( mp , 0 , sizeof ( mp ));
            LL ans = 0;
            for ( int i = 1 ; i <= n ; i++ )
            {
                int x = s^dp[i];
                mp[dp[i]]++;
                ans += mp[x];
            }
            printf ( "%I64d\n" , ans );
        }
    }
}

你可能感兴趣的:(dp,多校)