C. Kefa and Park
#include <bits/stdc++.h>
using namespace std;
class Tree {
public:
int n, m, ans;
vector<vector<int>> adj;
vector<int> has_cat;
Tree(int n, int m) {
this->n = n;
this->m = m;
ans = 0;
adj.resize(n);
has_cat.resize(n);
}
void dfs(int src, int par, int cons_cat_count, bool ok) {
if (has_cat[src]) {
cons_cat_count++;
}
if (cons_cat_count > m) {
ok = false;
}
if (!has_cat[src]) {
cons_cat_count = 0;
}
// Add contribution if it is a leaf vertex.
// To identify a leaf vertex:
// 1. It should not be root.
// 2. It should have exactly one element in adjacency list.
if (ok && par != -1 && adj[src].size() == 1) {
ans++;
}
for (auto child : adj[src]) {
if (child != par) {
dfs(child, src, cons_cat_count, ok);
}
}
}
};
void solve() {
int n, m;
cin >> n >> m;
Tree t(n, m);
for (int i = 0; i < n; i++) {
cin >> t.has_cat[i];
}
auto &adj = t.adj;
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
adj[x].push_back(y);
adj[y].push_back(x);
}
t.dfs(0, -1, 0, true);
cout << t.ans << endl;
}
int main() {
solve();
return 0;
}
#include <bits/stdc++.h>
using namespace std;
class Tree {
public:
int n, m, ans;
vector<vector<int>> adj;
vector<int> has_cat;
Tree(int n, int m) {
this->n = n;
this->m = m;
ans = 0;
adj.resize(n);
has_cat.resize(n);
}
void dfs(int src, int par, int cons_cat_count) {
cons_cat_count += has_cat[src];
if (cons_cat_count > m) {
return;
}
if (!has_cat[src]) {
cons_cat_count = 0;
}
// Add contribution if it is a leaf vertex.
// To identify a leaf vertex:
// 1. It should not be root.
// 2. It should have exactly one element in adjacency list.
if (par != -1 && adj[src].size() == 1) {
ans++;
}
for (auto child : adj[src]) {
if (child != par) {
dfs(child, src, cons_cat_count);
}
}
}
};
void solve() {
int n, m;
cin >> n >> m;
Tree t(n, m);
for (int i = 0; i < n; i++) {
cin >> t.has_cat[i];
}
auto &adj = t.adj;
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
adj[x].push_back(y);
adj[y].push_back(x);
}
t.dfs(0, -1, 0);
cout << t.ans << endl;
}
int main() {
solve();
return 0;
}