This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ar array
struct Dsu{
vector <int> fa;
Dsu(int n){
fa.resize(n);
iota(fa.begin(), fa.end(), 0);
}
int get(int x){ return x ^ fa[x] ? fa[x] = get(fa[x]) : x; }
bool merge(int u, int v){
u = get(u), v = get(v);
if ( u == v ) return false;
fa[v] = u;
return true;
}
};
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, k; cin >> n >> k;
vector <vector<int>> adj(n);
for ( int i = 0; i + 1 < n; i++ ){
int u, v; cin >> u >> v;
--u, --v;
adj[u].pb(v);
adj[v].pb(u);
}
vector <int> s(n);
for ( auto &x: s ){
cin >> x; --x;
}
vector <vector<int>> cnt(n, vector <int> (k));
auto dfs = [&](auto dfs, int u, int p) -> void{
cnt[u][s[u]] = 1;
for ( auto &v: adj[u] ){
if ( v != p ){
dfs(dfs, v, u);
for ( int i = 0; i < k; i++ ){
cnt[u][i] += cnt[v][i];
}
}
}
};
dfs(dfs, 0, -1);
vector <int> bad(n);
for ( int u = 0; u < n; u++ ){
bool flag = true;
for ( int t = 0; t < k; t++ ){
if ( cnt[u][t] > 0 && cnt[u][t] < cnt[0][t] ){
flag = false;
}
}
bad[u] = flag;
}
vector <int> sub(n);
auto cals = [&](auto cals, int u, int p) -> void{
sub[u] = bad[u];
for ( auto &v: adj[u] ){
if ( v != p ){
cals(cals, v, u);
sub[u] += sub[v];
}
}
};
cals(cals, 0, -1);
int num = 0;
for ( int u = 1; u < n; u++ ){
if ( !bad[u] ) continue;
if ( sub[u] == sub[0] || sub[u] == 1 ){
num += 1;
}
}
cout << (num + 1) / 2;
cout << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |