Source Code
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rand(int l, int r)
{
    return uniform_int_distribution<int>(l, r)(rng);
}
#define F first
#define S second
#define p1 2*p
#define p2 p1+1
#define ll long long
#define pb push_back
#define LFT p1,L,Mid
#define pf push_front
#define Mid ((L+R)/2)
#define RGT p2,Mid+1,R
#define pi pair<int,int>
#define pii pair<int,pi>
#define deb(x) cout<<#x<<"="<<x<<endl
#define go ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
const int M = 30;
const int N = 100100;
const int mod = 1e9 + 7;
int mul(int x,int y)
{
    return (ll) x*y %mod;
}
int sum(int x,int y)
{
    if((x+=y)>=mod)
        x-=mod;
    return x;
}
int sub(int x,int y)
{
    if((x-=y)<0)
        x+=mod;
    return x;
}
int po(int x,int y)
{
    if(!y)  return 1;
    if(y&1) return mul(x,po(x,y-1));
    int z=po(x,y/2);
    return mul(z,z);
}
int inv(int x)
{
    return po(x,mod-2);
}
int n,dp[2][N][M],cnt[2][M][2],ans;
vector <pi> adj[2][N];
void dfs(int i,int u,int p,int xo)
{
    for(int j=0; j<M; j++)
    {
        dp[i][u][j]=((xo>>j)&1);
        cnt[i][j][dp[i][u][j]]++;
    }
    for(pi x : adj[i][u])
        if(x.F!=p)
            dfs(i,x.F,u,xo^x.S);
}
int main()
{
    go;
    cin>>n;
    for(int i=1,a,b,c; i<n; i++)
    {
        cin>>a>>b>>c;
        adj[0][a].pb({b,c});
        adj[0][b].pb({a,c});
    }
    for(int i=1,a,b,c; i<n; i++)
    {
        cin>>a>>b>>c;
        adj[1][a].pb({b,c});
        adj[1][b].pb({a,c});
    }
    dfs(0,1,0,0);
    dfs(1,1,0,0);
    for(int i=1; i<=n; i++)
    {
        int two=1;
        for(int j=0; j<M; j++)
        {
            int x3=dp[0][i][j];
            int x4=dp[1][i][j];
            for(int x1 : {0,1})
                for(int x2 : {0,1})
                {
                    int res=mul(two,x1^x2^x3^x4);
                    int cnt1=cnt[0][j][x1];
                    int cnt2=cnt[1][j][x2];
                    res=mul(res,mul(cnt1,cnt2));
                    ans=sum(ans,res);
                }
            two=sum(two,two);
        }
    }
    cout<<ans<<'\n';
    return 0;
}
Copy
Trees xOr Grapeee
GNU G++17
430 ms
36.0 MB
Accepted