///#include "happy.h"
#include <iostream>
#include <vector>
#include <queue>

std::vector<std::pair<int , int>> g[300001];
int deschis[300001];
long long dist[100001][100001];
int viz[100001][100001];

void dijkstra(int x)
{
    std::priority_queue<std::pair<int , int>> p;
    p.push({0 , x});
    dist[x][x] = 0;
    while (p.size() > 0)
    {
        int nod1 = p.top().second;
        p.pop();
        if (viz[x][nod1] == 0)
        {
            viz[x][nod1] = 1;
            for (int i = 0; i < g[nod1].size(); i++)
            {
                int nod2 = g[nod1][i].first;
                int cost = g[nod1][i].second;
                if ((dist[x][nod1] ^ cost) < dist[x][nod2])
                {
                    dist[x][nod2] = dist[x][nod1] ^ cost;
                    p.push({-dist[x][nod2] , nod2});
                }
            }
        }
    }
}

std::vector <long long int> happy (int N, int Q, std::vector <int> u, std::vector <int> v, std::vector <int> h, std::vector <int> t, std::vector <int> l, std::vector <int> r)
{
    int n = N;
    int q = Q;
    for (int i = 0; i < n - 1; i++)
    {
        g[u[i] + 1].push_back({v[i] + 1 , h[i]});
        g[v[i] + 1].push_back({u[i] + 1 , h[i]});
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            dist[i][j] = 1e18;
        }
    }
    for (int j = 1; j <= n; j++)
    {
        dijkstra(j);
    }
    std::vector<long long int> rez;
    for (int i = 0; i < q; i++)
    {
        for (int j = l[i] + 1; j <= r[i] + 1; j++)
        {
            if (t[i] == 1)
            {
                deschis[j] = 1;
            }
            else
            {
                deschis[j] = 0;
            }
        }

        long long nr = 0;
        for (int j = 1; j <= n; j++)
        {
            for (int k = j + 1; k <= n; k++)
            {
                if (deschis[j] == 1 && deschis[k] == 1)
                {
                    nr += dist[j][k];
                }
            }
        }
        rez.push_back(nr);
    }
    return rez;
}