#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAXN = (int)(5e5) + 5;
vector<int> adj[MAXN];
int up[MAXN][21];
int timer = 0;
int tin[MAXN];
int tout[MAXN];
int S[MAXN];
int last[MAXN];
int lcm[MAXN];
int cnt[MAXN];
void root(int n, int p) {
tin[n] = timer++;
up[n][0] = p;
for (int k = 1; k <= 20; k++) {
up[n][k] = up[up[n][k-1]][k-1];
}
for (int e : adj[n]) {
if (e != p) {
root(e, n);
}
}
tout[n] = timer++;
}
int dfs(int n, int p) {
int paths = 0;
for (int e : adj[n]) {
if (e != p) {
paths += dfs(e, n);
cnt[n] += cnt[e];
}
}
if (cnt[n] == 0) {
if (paths == 0 && n != p) {
paths++;
}
}
return paths;
}
bool is_ancestor(int a, int b) {
return (tin[a] <= tin[b] && tout[a] >= tout[b]);
}
int lca(int a, int b) {
if (is_ancestor(a, b)) {
return a;
}
if (is_ancestor(b, a)) {
return b;
}
int u = a;
for (int k = 20; k >= 0; k--) {
if (!is_ancestor(up[u][k], b)) {
u = up[u][k];
}
}
return up[u][0];
}
int main() {
// string s = "input.in";
// freopen(s.c_str(), "r", stdin);
int N, s;
cin >> N >> s;
for (int i = 0; i < N-1; i++) {
int a, b;
cin >> a >> b;
a--, b--;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<int> df;
for (int i = 0; i < N; i++) {
df.push_back(i);
last[i] = -1;
cin >> S[i];
}
root(0, 0);
sort(df.begin(), df.end(), [](const int& lhs, const int& rhs) {
return tin[lhs] < tin[rhs];
}
);
for (int i : df) {
if (last[S[i]] == -1) {
last[S[i]] = i;
lcm[S[i]] = i;
}
else {
if (is_ancestor(lcm[S[i]], i)) {
cnt[i]++;
cnt[lcm[S[i]]]--;
}
else {
int lc = lca(lcm[S[i]], i);
cnt[S[i]]++;
cnt[lc]-=2;
cnt[i]++;
lcm[S[i]] = lc;
}
}
}
cout << (dfs(0, 0)+1)/2;
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
8 ms |
12140 KB |
Output is correct |
2 |
Incorrect |
9 ms |
12140 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
8 ms |
12140 KB |
Output is correct |
2 |
Incorrect |
9 ms |
12140 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
8 ms |
12140 KB |
Output is correct |
2 |
Incorrect |
9 ms |
12140 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
143 ms |
27748 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
8 ms |
12140 KB |
Output is correct |
2 |
Incorrect |
9 ms |
12140 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |