#include <bits/stdc++.h>
#define pb emplace_back
using namespace std;
#define debug(args...) kout("[ " + string(#args) + " ]", args)
void kout() { cerr << endl; }
template <class T, class ...U> void kout(T a, U ...b) { cerr << a << ' ',kout(b...); }
template <class T> void pary(T L, T R) { while (L != R) cerr << *L << " \n"[++L==R]; }
const int MAXN = 500000;
int N, K;
int a, b;
vector <int> path[MAXN+1];
vector <int> G[MAXN+1];
int v[MAXN+1];
int dsu[MAXN+1];
int sze[MAXN+1];
bool vis[MAXN+1];
int k[MAXN+1];
int ans = -1;
int fnd(int a) {
return dsu[a] == a ? a : dsu[a] = fnd(dsu[a]);
}
void Merge(int a, int b) {
a = fnd(a), b = fnd(b);
if (a == b) return;
if (sze[a] > sze[b]) {
dsu[b] = a;
sze[a] += sze[b];
} else {
dsu[a] = b;
sze[b] += sze[a];
}
}
void BFS(int st) {
for (int i = 1; i <= N; i++)
k[i] = 0;
k[st] = st;
queue <int> nxt;
nxt.push(st);
while (nxt.size()) {
int now = nxt.front();
nxt.pop();
for (int i : path[now]) {
if (!k[i]) {
k[i] = now;
nxt.push(i);
}
}
}
for (int i = 1; i <= N; i++) {
if (v[i] != v[st]) continue;
int t = i;
while (k[t] != t) {
if (fnd(t) == fnd(st)) break;
Merge(t, k[t]);
t = k[t];
}
}
}
signed main() {
ios_base::sync_with_stdio(0), cin.tie(0);
cin >> N >> K;
for (int i = 1; i < N; i++) {
cin >> a >> b;
path[a].pb(b);
path[b].pb(a);
}
for (int i = 1; i <= N; i++) {
cin >> v[i];
dsu[i] = i;
sze[i] = 1;
}
for (int i = 1; i <= K; i++) {
if (vis[v[i]]) continue;
BFS(i);
vis[v[i]] = true;
}
for (int i = 1; i <= N; i++) {
for (int j : path[i]) {
if (fnd(i) != fnd(j)) G[fnd(i)].pb(fnd(j));
}
}
for (int i = 1; i <= N; i++) {
if (!G[i].size()) continue;
bool flag = true;
for (int j : G[i])
flag &= (j == G[i][0]);
if (flag) ans++;
}
cout << max(0, ans) << '\n';
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
17 ms |
23936 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
17 ms |
23936 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
17 ms |
23936 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
153 ms |
30132 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
17 ms |
23936 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |