#include "happy.h"
#include <bits/stdc++.h>
using namespace std;

void dfs(int cur, int prev, vector<int> &dist, vector<vector<pair<int, int> > > &g)
{
    for(pair<int, int> &state : g[cur])
    {
        int next = state.first;
        int edge = state.second;

        if(next == prev)continue;
        dist[next] = (dist[cur] ^ edge);
        dfs(next, cur, dist, g);
    }
}

vector<long long int> happy (int N, int Q,
vector<int> u, vector<int> v, vector<int> h,
vector<int> t, vector<int> l, vector<int> r)
{
    int n = N;
    vector<int> open(n, 0);
    vector<long long> rez;

    vector<vector<pair<int, int> > > g(n);

    for(int i=0; i<n-1; i++)
    {
        int U = u[i];
        int V = v[i];
        int H = h[i];

        g[U].push_back({V, H});
        g[V].push_back({U, H});
    }

    for(int q = 0; q < Q; q++)
    {
        int curL = l[q], curR = r[q], curT = t[q];
        for(int i=curL; i<=curR; i++)open[i] = curT % 2;

        vector<vector<int> > dist(n, vector<int>(n, 0));
        for(int i=0; i<n; i++)if(open[i])dfs(i, -1, dist[i], g);

        long long sum = 0;
        for(int i=0; i<n-1; i++)
        {
            if(!open[i])continue;

            for(int j=i+1; j<n; j++)
            {
                if(!open[j])continue;
                sum += (long long)dist[i][j];
            }
        }
        rez.push_back(sum);
    }

    return rez;
}