#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define x first
#define y second
#define all(v) v.begin(),v.end()
#define clr(v,d) memset(v,d,sizeof(v));
const int N = 1e5 + 10;
const ll mod = 1e9 + 7;
int numCh1[N] , numCh2[N] , n ;
vector<pair<int ,int > > ad1[N] , ad2[N];
vector<vector<ll> > num1(N , vector<ll> (30) ) , num2(N , vector<ll> (30) ) ;
void cal1(int i , int p)
{
numCh1[i] = 1;
for(pair<int ,int > ch : ad1[i])
{
if(ch.x != p)
{
cal1(ch.x , i);
numCh1[i] += numCh1[ch.x];
for (int j = 0; j < 30; ++j) {
if(( ch.y >> j ) & 1)
{
num1[i][j] += numCh1[ch.x] - num1[ch.x][j] ;
}
else num1[i][j] += num1[ch.x][j];
}
}
}
}
void cal2(int i , int p)
{
numCh2[i] = 1;
for(pair<int ,int > ch : ad2[i])
{
if(ch.x != p)
{
cal2(ch.x , i);
numCh2[i] += numCh2[ch.x];
for (int j = 0; j < 30; ++j) {
if((ch.y >> j ) & 1)
{
num2[i][j] += numCh2[ch.x] - num2[ch.x][j] ;
}
else num2[i][j] += num2[ch.x][j];
}
}
}
}
void dfs1(int i ,int p )
{
for(pair<int ,int > ch : ad1[i])
{
if(ch.x == p) continue;
for (int j = 0; j < 30; ++j) {
int by_me = ((ch.y >> j)&1)? numCh1[ch.x]-num1[ch.x][j] : num1[ch.x][j] ;
if((ch.y >> j) & 1)
{
num1[ch.x][j] += (numCh1[i] - numCh1[ch.x]) - (num1[i][j] - by_me) ;
}
else num1[ch.x][j] += (num1[i][j] - by_me) ;
}
numCh1[ch.x] += numCh1[i] - numCh1[ch.x] ;
dfs1(ch.x , i);
}
}
void dfs2(int i ,int p )
{
for(pair<int ,int > ch : ad2[i])
{
if(ch.x == p) continue;
for (int j = 0; j < 30; ++j) {
int by_me = ((ch.y >> j)&1)? numCh2[ch.x]-num2[ch.x][j] : num2[ch.x][j] ;
if((ch.y >> j) & 1)
{
num2[ch.x][j] += (numCh2[i] - numCh2[ch.x]) - (num2[i][j] - by_me) ;
}
else num2[ch.x][j] += (num2[i][j] - by_me) ;
}
numCh2[ch.x] += numCh2[i] - numCh2[ch.x] ;
dfs2(ch.x , i);
}
}
int main()
{
cin.tie(0);
cin.sync_with_stdio(0);
cin >> n;
for (int i = 0; i < n - 1; ++i) {
int u , v ,w;
cin >> u >> v >> w;
ad1[u].push_back({v,w});
ad1[v].push_back({u,w});
}
for (int i = 0; i < n - 1; ++i) {
int u , v ,w;
cin >> u >> v >> w;
ad2[u].push_back({v,w});
ad2[v].push_back({u,w});
}
cal1(1 , 0) , cal2(1 , 0);
dfs1(1,0);
dfs2(1 , 0) ;
ll ans = 0;
for(int i = 1 ; i <= n ; i++)
{
for (int j = 0; j < 30; ++j) {
ll te = (1ll << j)*num1[i][j] ;
te %= mod ;
te *= n - num2[i][j] ;
ans += te % mod ;
ans %= mod ;
te = (1ll << j)*num2[i][j] ;
te %= mod ;
te *= n - num1[i][j] ;
ans += te % mod ;
ans %= mod ;
}
}
cout << ans ;
return 0;
}
Copy