#include <bits/stdc++.h>
using namespace std;
#define ll long long
struct custom_hash
{
static uint64_t splitMix64(uint64_t x)
{
// http://x...content-available-to-author-only...i.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
template<typename T1, typename T2>
size_t operator()(const pair<T1,T2>& x) const
{
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitMix64(x.first + FIXED_RANDOM) ^ (splitMix64(x.second + FIXED_RANDOM) << 1);
}
};
struct Node
{
ll Value;
Node *LeftChild, *RightChild; // Pointers to left child and right child
Node(const ll &val = 0)
{
Value = val;
LeftChild = nullptr;
RightChild = nullptr;
}
~Node() // Destructor. Notice the "~" character before the struct name.
{
delete LeftChild;
delete RightChild;
LeftChild = nullptr;
RightChild = nullptr;
}
};
int M;
unordered_map<pair<int,ll>, int, custom_hash> subtreeMap; // {hash -> {size, sum}}
bool check = false;
pair<int, ll> dfs(Node *root)
{
if (root == nullptr)
return {0, 0};
const auto &left = dfs(root->LeftChild);
const auto &right = dfs(root->RightChild);
int size = 1 + left.first + right.first;
ll sum = root->Value + left.second + right.second;
if (size > M)
{
if (subtreeMap.count({size, sum}))
check = true;
else
subtreeMap[{size, sum}]++;
}
return {size, sum};
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin >> N >> M;
vector<int> nodes(N);
for (int i = 0; i < N; i++)
cin >> nodes[i];
vector<Node *> tree;
for (int i = 0; i < N; i++)
tree.push_back(new Node(nodes[i]));
int E;
cin >> E;
for (int i = 0; i < E; i++)
{
char dir;
int parentIdx, childIdx;
cin >> dir >> parentIdx >> childIdx;
if (dir == 'L')
tree[parentIdx]->LeftChild = tree[childIdx];
else
tree[parentIdx]->RightChild = tree[childIdx];
}
Node *root = tree[0]; // Root node
dfs(root);
cout << check;
return 0;
}
I2luY2x1ZGUgPGJpdHM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