#include <bits/stdc++.h>
#define all(i) i.begin(), i.end()
#define rall(i) i.rbegin(), i.rend()
using namespace std;
typedef long long ll;
typedef pair<int, int> pi;
const ll mod = 1e9 + 7;
vector<vector<int>> g;
vector<int> rt, low;
vector<bool> vis;
void dfs(int i, int p, int d) {
vis[i] = true, low[i] = d;
for (int j : g[i]) if (j != p) {
if (!vis[j]) dfs(j, i, d + 1);
low[i] = min(low[i], low[j]);
}
rt[i] = low[i] < d ? p : i;
}
int find(int i) {
return rt[i] = rt[i] == i ? i : find(rt[i]);
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
int n, k;
cin >> n >> k;
g.resize(n), rt.resize(n), low.resize(n), vis.assign(n, false);
for (int i = 0; i < n - 1; ++i) {
int x, y;
cin >> x >> y;
--x, --y;
g[x].push_back(y), g[y].push_back(x);
}
vector<int> last(k, -1);
for (int i = 0, x; i < n; ++i) {
cin >> x, --x;
if (~last[x])
g[i].push_back(last[x]), g[last[x]].push_back(i);
last[x] = i;
}
dfs(0, 0, 0);
for (int i = 0; i < n; ++i) find(i);
for (int i = 0; i < n; ++i) {
for (int &j : g[i]) j = rt[j];
if (rt[i] != i) for (int &j : g[i]) g[rt[i]].push_back(j);
}
int cc = 0, lf = 0;
for (int i = 0; i < n; ++i) if (rt[i] == i) {
++cc, g[i].resize(unique(all(g[i])) - g[i].begin());
if (g[i].size() == 1) ++lf;
}
if (lf == 1) return cout << 0, 0;
cout << (lf + 1 >> 1);
}
Compilation message
mergers.cpp: In function 'int main()':
mergers.cpp:52:17: warning: suggest parentheses around '+' inside '>>' [-Wparentheses]
52 | cout << (lf + 1 >> 1);
| ~~~^~~
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Incorrect |
1 ms |
364 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Incorrect |
1 ms |
364 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Incorrect |
1 ms |
364 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
88 ms |
10852 KB |
Output is correct |
2 |
Correct |
66 ms |
9188 KB |
Output is correct |
3 |
Incorrect |
3 ms |
620 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Incorrect |
1 ms |
364 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |