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;
void abc() {cout << endl;}
template <typename T, typename ...U> void abc(T a, U ...b) {
cout << a << ' ', abc(b...);
}
template <typename T> void printv(T l, T r) {
while (l != r) cout << *l << " \n"[++l == r];
}
template <typename A, typename B> istream& operator >> (istream& o, pair<A, B> &a) {
return o >> a.first >> a.second;
}
template <typename A, typename B> ostream& operator << (ostream& o, pair<A, B> a) {
return o << '(' << a.first << ", " << a.second << ')';
}
template <typename T> ostream& operator << (ostream& o, vector<T> a) {
bool is = false;
for (T i : a) {o << (is ? ' ' : '{'), is = true, o << i;}
return o << '}';
}
#ifdef local
#define test(args...) abc("[" + string(#args) + "]", args)
#else
#define test(args...) void(0)
#endif
using ll = long long;
vector<int> adj[500005];
int par[500005];
vector<int> group[500005];
int depth[500005];
void dfs(int node, int parr = -1) {
for (auto nxt : adj[node]) {
if (nxt == parr) continue;
par[nxt] = node;
depth[nxt] = depth[node] + 1;
dfs(nxt, node);
}
}
int pr[500005];
int deg[500005];
int findset(int i) {
if (pr[i] == i) return i;
return pr[i] = findset(pr[i]);
}
void merge(int a, int b) {
while (a != b) {
if (depth[a] < depth[b]) swap(a, b);
pr[a] = findset(par[a]);
a = pr[a];
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
// freopen("", "r", stdin);
// freopen("", "w", stdout);
int n, k; cin >> n >> k;
for (int i = 0; i < n - 1; i++) {
int a, b; cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int i = 1; i <= n; i++) pr[i] = i;
for (int i = 1; i <= n; i++) {
int temp; cin >> temp;
group[temp].push_back(i);
}
depth[1] = 1;
dfs(1);
for (int i = 1; i <= n; i++) {
if (group[i].empty()) continue;
for (int j = 1; j < group[i].size(); j++) {
merge(group[i][0], group[i][j]);
}
}
for (int i = 1; i <= n; i++) {
for (auto j : adj[i]) {
if (findset(i) != findset(j)) {
deg[findset(i)]++;
deg[findset(j)]++;
}
}
}
int ct = 0;
for (int i = 1; i <= n; i++) {
if (deg[i] == 2) ct++;
}
cout << (ct + 1) / 2;
}
Compilation message (stderr)
mergers.cpp: In function 'int main()':
mergers.cpp:88:27: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
88 | for (int j = 1; j < group[i].size(); j++) {
| ~~^~~~~~~~~~~~~~~~~
# | 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... |