|
| 1 | +#include <bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +using ll = long long; |
| 6 | +#define ii pair<int, int> |
| 7 | +#define f first |
| 8 | +#define s second |
| 9 | +#define pb push_back |
| 10 | +#define mp make_pair |
| 11 | +#define all(x) x.begin(), x.end() |
| 12 | +#define sz(x) (int)x.size() |
| 13 | +#define F0R(i, n) for (int i = 0; i < n; i++) |
| 14 | +#define FOR(i, a, b) for (int i = a; i < b; i++) |
| 15 | +#define inf 1000000010 |
| 16 | + |
| 17 | +vector<int> adj[800000]; |
| 18 | +int par[800000][20]; |
| 19 | +int depth[800000]; |
| 20 | +int minDepth[800000]; |
| 21 | + |
| 22 | +void dfs(int u, int p, int d = 0) { |
| 23 | + depth[u] = d; |
| 24 | + minDepth[u] = d; |
| 25 | + par[u][0] = p; |
| 26 | + for (int v : adj[u]) { |
| 27 | + if (v != p) { |
| 28 | + dfs(v, u, d+1); |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +void dfs2(int u, int p) { |
| 34 | + for (int v : adj[u]) { |
| 35 | + if (v != p) { |
| 36 | + dfs2(v, u); |
| 37 | + minDepth[u] = min(minDepth[u], minDepth[v]); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +int lca(int a, int b) { |
| 43 | + if (depth[a] < depth[b]) swap(a, b); |
| 44 | + for (int i = 19; ~i; i--) { |
| 45 | + if (depth[par[a][i]] >= depth[b]) { |
| 46 | + a = par[a][i]; |
| 47 | + } |
| 48 | + } |
| 49 | + if (a == b) return a; |
| 50 | + for (int i = 19; ~i; i--) { |
| 51 | + if (par[a][i] != par[b][i]) { |
| 52 | + a = par[a][i]; |
| 53 | + b = par[b][i]; |
| 54 | + } |
| 55 | + } |
| 56 | + assert(par[a][0] == par[b][0]); |
| 57 | + return par[a][0]; |
| 58 | +} |
| 59 | + |
| 60 | +int main() { |
| 61 | + cin.tie(0)->sync_with_stdio(0); |
| 62 | + |
| 63 | + int t; cin >> t; |
| 64 | + for (int tc = 1; tc <= t; tc++) { |
| 65 | + cout << "Case #" << tc << ": "; |
| 66 | + |
| 67 | + int n; cin >> n; |
| 68 | + for (int i = 0; i < n; i++) adj[i].clear(); |
| 69 | + for (int i = 0; i < n-1; i++) { |
| 70 | + int a, b; cin >> a >> b; --a; --b; |
| 71 | + adj[a].pb(b); adj[b].pb(a); |
| 72 | + } |
| 73 | + |
| 74 | + dfs(0, 0); |
| 75 | + for (int d = 1; d < 20; d++) { |
| 76 | + for (int i = 0; i < n;i ++) { |
| 77 | + par[i][d] = par[par[i][d-1]][d-1]; |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + map<int, vector<int>> freqs; |
| 82 | + for (int i = 0; i < n; i++) { |
| 83 | + int f; cin >> f; freqs[f].pb(i); |
| 84 | + } |
| 85 | + for (auto &x : freqs) { |
| 86 | + for (int i = 1; i < x.s.size(); i++) { |
| 87 | + int a = x.s[0], b = x.s[i]; |
| 88 | + assert(a != b); |
| 89 | + int y = lca(a, b); |
| 90 | + minDepth[a] = min(minDepth[a], depth[y]); |
| 91 | + minDepth[b] = min(minDepth[b], depth[y]); |
| 92 | + } |
| 93 | + } |
| 94 | + dfs2(0, 0); |
| 95 | + |
| 96 | + int ans = 0; |
| 97 | + for (int i = 1; i < n; i++) { |
| 98 | + if (minDepth[i] == depth[i]) ans++; |
| 99 | + } |
| 100 | + cout << ans << endl; |
| 101 | + } |
| 102 | + |
| 103 | + return 0; |
| 104 | +} |
0 commit comments