Source Code
#include <bits/stdc++.h>

#define ll long long
#define ull unsigned ll
constexpr auto PI = 3.141592653589793238462643383279502884;

const ll  MM = 1e9+7, N = 2e5 + 10;
const ll MAX = 2e16;
using namespace std;

ll gcd(ll a, ll b) {
	if (a < b)swap(a, b);
	if (b == 0)return a;
	return gcd(b, a % b);
}
ll lcm(ll a, ll b) {
	return a * b / gcd(a, b);
}
ll numberOfDiviser(ll a) {
	if (a == 1)return 0;
	ll ans = 1;
	ll i;
	for (i = 2; i * i < a; i++) {
		if (a % i == 0)ans += 2;
	}
	if (i * i == a)ans++;
	return ans;
}

ll pow(ll a, ll b, ll m) {
	if (b == 0)return 1;
	if (b == 1)return a;
	ll x = pow(a, b / 2, m);
	x = (x * x) % m;
	if (b % 2)x = (x * a);
	return x % m;
}
ll inverse_mod(ll a, ll m) {
	return pow(a, m - 2, m);
}
vector<pair<ll,ll>>v[2][N];
ll cnt[2][N][35][2];

pair<ll,ll> dfs(int tree,int i, int p, int mask, int zero, int one) {
	pair<ll, ll>cc = { 1,0 };
	for (auto x : v[tree][i]) {
		if (x.first == p)continue;
		if (x.second & (1ll << mask)) {
			pair<ll,ll>temp=dfs(tree,x.first, i, mask, one, zero + 1);
			cc.first += temp.second;
			cc.second += temp.first;
		}
		else {
			pair<ll, ll>temp = dfs(tree,x.first, i, mask, zero + 1, one);
			cc.first += temp.first;
			cc.second += temp.second;
		}
	}
	cnt[tree][i][mask][0] = cc.first + zero;
	cnt[tree][i][mask][1] = cc.second + one;
	return cc;
}


int solve() {
	int n; cin >> n;
	int x, y, w;
	for (int i = 1; i < n; i++) {
		cin >> x >> y >> w;
		v[0][x].emplace_back(y, w);
		v[0][y].emplace_back(x, w);
	}
	for (int i = 1; i < n; i++) {
		cin >> x >> y >> w;
		v[1][x].emplace_back(y, w);
		v[1][y].emplace_back(x, w);
	}
	int st, st1;
	for (int i = 1; i <= n; i++) {
		if (v[0][i].size() == 1)st = i;
		if (v[1][i].size() == 1)st1 = i;
	}
	for (int i = 0; i < 35; i++) {
		dfs(0, st, -1, i, 0, 0);
		dfs(1, st1, -1, i, 0, 0);
	}
	
	ll res = 0;

	for (int i = 1; i <= n; i++) {
		for (ll mask = 0; mask < 35; mask++) {
			res += cnt[0][i][mask][0] * cnt[1][i][mask][1]%MM*(1ll<<mask)%MM;
			res += cnt[0][i][mask][1] * cnt[1][i][mask][0]%MM*(1ll<<mask)%MM;
		}
	}
	cout << res << '\n';
	return 0;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	std::cout.tie(0);
	int t = 1;//cin >> t;
	int i = 1;
	while (t--) {
		//cout << "Case #" << i++ << ": ";
		solve();
	}
}
/*

*/
Copy
Trees xOr srdamaa7
GNU G++17
14 ms
9.8 MB
Wrong Answer