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

using namespace std;

typedef long long ll;

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) {
    vector<int> open(N, 0);
    vector<pair<int, int>> adj[N];
    vector<long long int> rez;
    for (int i = 0; i < N; i++) {
        adj[u[i]].push_back({v[i], h[i]});
        adj[v[i]].push_back({u[i], h[i]});
    }

    for (int k = 0; k < Q; k++) {
        vector<int> val;
        if (t[k] == 1) {
            for (int j = l[k]; j <= r[k]; j++) {
                open[j] = 1;
            }
        } else {
            for (int j = l[k]; j <= r[k]; j++) {
                open[j] = 0;
            }
        }

        for (int i = 0; i < N; i++) {
            if (open[i] == 1) {
                for (int j = i + 1; j < N; j++) {
                    if (open[j] == 1) {
                        vector<bool> visited(N, false);
                        queue<pair<int, int>> q;
                        for (auto [x, happy] : adj[i]) {
                            q.push({i, happy});
                        }
                        visited[i] = true;

                        while (!q.empty()) {
                            int curr = q.front().first, happy = q.front().second;
                            q.pop();

                            if (curr = j) {
                                val.push_back(happy);
                                break;
                            }

                            for (auto [x, w] : adj[curr]) {
                                if (!visited[x]) {
                                    q.push({x, (happy^w)});
                                    visited[x] = true;
                                }
                            }
                        }
                    }
                }
            }
            long long int ans = 0;
            for (int x : val) {
                ans += x;
            }
            rez.push_back(ans);
        }
    }

    return rez;
}
