#include <bits/stdc++.h>
using namespace std;
vector<long long> happy(int n, int q, vector<int> u, vector<int> v, vector<int> h, vector<int> t, vector<int> l, vector<int> r) {
    vector<vector<pair<int, long long>>> graph(n + 1);
    for (int i = 0; i < n - 1; i++) {
        graph[u[i] + 1].push_back({v[i] + 1, h[i]});
        graph[v[i] + 1].push_back({u[i] + 1, h[i]});
    }
    vector<vector<long long>> path(n + 1, vector<long long>(n + 1, -1));
    for (int i = 1; i <= n; i++) {
        path[i][i] = 0;
    }
    for (int i = 1; i <= n; i++) {
        queue<long long> qu;
        qu.push(i);
        while (!qu.empty()) {
            int u = qu.front();
            qu.pop();
            for (auto [v, w2] : graph[u]) {
                if (path[i][v] == -1) {
                    path[i][v] = path[i][u] ^ w2;
                    qu.push(v);
                }
            }
        }
    }
    vector<long long> ans;
    vector<bool> stat(n + 1, 0);
    long long sum = 0;
    for (int i = 0; i < q; i++) {
        l[i]++; r[i]++;
        if (t[i] == 1) {
            for (int j = l[i]; j <= r[i]; j++) {
                if (!stat[j]) {
                    stat[j] = true;
                    for (int k = 1; k <= n; k++) {
                        if (stat[k]) {
                            sum += path[k][j];
                        }
                    }
                }
            }
        } else {
            for (int j = l[i]; j <= r[i]; j++) {
                if (stat[j]) {
                    stat[j] = false;
                    for (int k = 1; k <= n; k++) {
                        if (stat[k]) {
                            sum -= path[k][j];
                        }
                    }
                }
            }
        }
        ans.push_back(sum);
    }
    return ans;
}
