Source Code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;

#define forr(_a, _b, _c) for(_a = (_b); _a <= (_c); ++_a)
#define ford(_a, _b, _c) for(_a = (_b) + 1; _a --> (_c);)
#define forf(_a, _b, _c) for(_a = (_b); _a < (_c); ++_a)
#define mp make_pair
#define fi first
#define se second
#define vi vector
#define sz(_v) _v.begin(), _v.end()
#define mask(_x) (1ll << (_x))
#define bit(_x,_y) (((_x) >> (_y)) & 1)

string yes[2] = {"NO\n","YES\n"};
const ld eps = ld(1e-7);
const ll inf = ll(1e16) + 1;
const ll mod = ll(1e9) + 7;

const int N = 2e5 + 5;
int n, i, a[N], f[N], g[N], x, y, z, j;
vi<pair<int,int> > adj[N];
ll c1[2], c2[2], o, t;

void dfs(int x, int tr) {
	int y, z, j;
	forf(j,0,adj[x].size()) {
		y = adj[x][j].fi;
		z = adj[x][j].se;
		if(y != tr) {
			g[y] = g[x] ^ z;
			dfs(y,x);
		}
	}
}

void get() {
	forr(i,1,n) {
		adj[i].clear();
	}
	forf(i,1,n) {
		cin >> x >> y >> z;
		adj[x].push_back(mp(y,z));
		adj[y].push_back(mp(x,z));
	}
	dfs(1,1);
}

void solve() {
	cin >> n;
	get();
	forr(i,1,n) f[i] = g[i];
	get();
	forf(j,0,30) {
		c1[0] = c1[1] = c2[0] = c2[1] = 0;
		forr(i,1,n) {
			++c1[bit(f[i],j)];
			++c2[bit(g[i],j)];
		}
		t = 0;
		forr(i,1,n) {
			if(bit(f[i],j) ^ bit(g[i],j)) {
				t += c1[1] * c2[1] + c1[0] * c2[0];
			} else {
				t += c1[1] * c2[0] + c1[0] * c2[1];
			}
		}
		(o += t % mod * mask(j)) %= mod;
	}
	cout << o;
}

void precalc() {
}

int main() {
	ios_base::sync_with_stdio(false); cin.tie(NULL);
	#ifdef umf
		freopen("test.inp","r",stdin);
		freopen("test.out","w",stdout);
	#endif

	int tc = 1;
	// cin >> tc;
	precalc();
	while(tc --> 0) {
		solve();
	}

	return 0;
}
Copy
Trees xOr thqdothabit
GNU G++17
114 ms
10.9 MB
Accepted