#include "happy.h"
#include<bits/stdc++.h>

using namespace std;

const int MAX_N = 2e4;

vector<pair<int, long long>> nbrs[MAX_N];
int dist[MAX_N][MAX_N];
int start;

void dfs(int u)
{
    for(auto [v, w] : nbrs[u])
    {
        if(dist[start][v] != -1) continue;
        dist[start][v] = dist[start][u] ^ w;
        dfs(v);
    }
}

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, q = Q;
    vector<long long> ansv;
    for(int i = 0; i < n - 1; ++i) {
        nbrs[u[i]].push_back({v[i], h[i]});
        nbrs[v[i]].push_back({u[i], h[i]});
    }

    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < n; ++j) {
            dist[i][j] = -1;
        }
    }

    for(int i = 0; i < n; ++i) {
        start = i;
        dist[i][i] = 0;
        dfs(i);
    }

    unordered_set<int> s;
    int curans = 0;
    for(int i = 0; i < q; ++i) {
        if(t[i] == 1)
        {
            for(int j = l[i]; j <= r[i]; ++j)
            {
                s.insert(j);
            }
            for(int j = l[i]; j <= r[i]; ++j) {
                for(auto x : s) {
                    curans += dist[x][j];
                }
            }
        }
        else
        {
            for(int j = l[i]; j <= r[i]; ++j)
            {
                s.erase(j);
            }
            for(int j = l[i]; j <= r[i]; ++j) {
                for(auto x : s) {
                    curans -= dist[x][j];
                }
            }
        }
        ansv.push_back(curans);
    }
    return ansv;
}
