#include <bits/stdc++.h>
#define N 1000000
using namespace std;
int range[N], n, k, city[N], ans[N], bef[N], pos, x[N], sda;
bool vis[N];
vector<int> adj[N], adjgraph[N];
vector<pair<int, int> > v;
void dfs(int node, int par = 0){
pos++;
// cout << endl;
// cout << pos << '\n';
x[pos] = city[node];
if(bef[city[node]] == 0){
range[pos] = pos;
bef[city[node]] = pos;
ans[city[node]] = 1;
}
else{
range[pos] = 1e9;
int val = pos - 1;
while(val > bef[city[node]]){
// cout << val << ' ';
if(range[val] > bef[city[node]]){
ans[city[node]] += ans[x[val]];
adjgraph[x[val]].push_back(city[node]);
}
else{
ans[city[node]] += (ans[x[val]] - 1);
}
range[pos] = min(range[pos], range[val]);
val = range[val] - 1;
}
// if(val < bef[city[node]]){
//
// }
// cout << val << '\n';
range[pos] = min(range[pos], range[bef[city[node]]]);
}
// cout << ans[city[node]] << '\n';
for(int neigh : adj[node]){
if(neigh != par) dfs(neigh, node);
}
}
void dfs1(int node){
vis[node] = 1;
ans[node] = sda;
for(int neigh : adjgraph[node]){
if(vis[neigh] == 0) dfs1(neigh);
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for(int i = 1; i < n; i++){
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int leaf;
for(int i = 1; i <= n; i++){
cin >> city[i];
if(adj[i].size() == 1) leaf = i;
}
dfs(leaf);
for(int i = 1; i <= k; i++){
v.push_back({ans[i], i});
}
sort(v.begin(), v.end());
for(int i = v.size() - 1; i >= 1; i--){
sda = v[i].first;
if(vis[v[i].second] == 0) dfs1(v[i].second);
}
int answer = 1e9;
for(int i = 1; i <= k; i++){
// cout << ans[i] << ' ';
answer = min(answer, ans[i] - 1);
}
// cout << '\n';
cout << answer;
}
Compilation message
capital_city.cpp: In function 'int main()':
capital_city.cpp:69:5: warning: 'leaf' may be used uninitialized in this function [-Wmaybe-uninitialized]
69 | dfs(leaf);
| ~~~^~~~~~
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
25 ms |
47308 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
25 ms |
47308 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
166 ms |
77240 KB |
Output is correct |
2 |
Correct |
129 ms |
77296 KB |
Output is correct |
3 |
Correct |
173 ms |
77244 KB |
Output is correct |
4 |
Correct |
112 ms |
77296 KB |
Output is correct |
5 |
Correct |
158 ms |
76900 KB |
Output is correct |
6 |
Correct |
117 ms |
77140 KB |
Output is correct |
7 |
Correct |
196 ms |
76724 KB |
Output is correct |
8 |
Correct |
116 ms |
76492 KB |
Output is correct |
9 |
Incorrect |
179 ms |
77908 KB |
Output isn't correct |
10 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
25 ms |
47308 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |