#include "happy.h"
#include <bits/stdc++.h>
using namespace std;
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)
{
    vector<bool>opened(N, false);
    vector<pair<int, int>>G[N];
    for(int i=0;i<N-1;i++)
    {
        G[u[i]].push_back({v[i], h[i]});
        G[v[i]].push_back({u[i], h[i]});
    }
    for(int i=0;i<Q;i++)
    {
        for(int j=l[i];j<=r[i];j++)
        {
            if(t[i]==1)
            {
                opened[j]=true;
            }
            else
            {
                opened[j]=false;
            }
        }
    }
    vector<int>bitni;
    for(int i=0;i<N;i++)
    {
        if(opened[i])
        {
            bitni.push_back(i);
        }
    }
    vector<long long int>V;
    for(int br : bitni)
    {
        long long int sum=0;
        long long dist[N];
        memset(dist, -1, sizeof(dist));
        queue<pair<int, int>>q;
        q.push({br, 0});
        dist[br]=0;
        while(!q.empty())
        {
            int node=q.front().first;
            int d=q.front().second;
            q.pop();
            for(auto next : G[node])
            {
                int neighbour=next.first;
                d=next.second;
                if(dist[neighbour]==-1)
                {
                    if(dist[node]==0)
                    {
                        dist[neighbour]=d;
                    }
                    else
                    {
                         dist[neighbour]=(dist[node] ^ d);
                         q.push({neighbour, dist[neighbour]});
                    }
                }
            }
        }
        for(int b : bitni)
        {
            sum+=dist[b];
        }
        V.push_back(sum);
    }
    return {V};
}
