#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> adj;
int C[200005];
int ma[200005];
int mi[200005];
int A[200005];
int B[200005];
bool vis[200005];
int DnC(int s, int e, set<int> Col) {
if(Col.size()==0 || e<=s) return 1e9;
if(s+1==e && Col.find(B[s])!=Col.end()) return 0;
int mid = (s+e)/2;
int l = mid, r = mid;
int pm = mi[B[mid]], pa = ma[B[mid]];
int val = 1e9;
if(Col.find(B[mid])!=Col.end()) {
set<int> S;
S.insert(B[mid]);
bool isPos = true;
while(pm < l || r < pa) {
while(pm < l) {
l--;
if(Col.find(B[l])==Col.end()) {
isPos = false;
break;
}
S.insert(B[l]);
pm = min(pm, mi[B[l]]);
pa = max(pa, ma[B[l]]);
}
if(!isPos) break;
while(r < pa) {
r++;
if(Col.find(B[r])==Col.end()) {
isPos = false;
break;
}
S.insert(B[r]);
pm = min(pm, mi[B[r]]);
pa = max(pa, ma[B[r]]);
}
if(!isPos) break;
}
if(isPos) val = min(val, (int)S.size());
}
set<int> S1, S2;
for(int n : Col) {
if(s<=mi[n]&&ma[n]<mid) S1.insert(n);
if(mid<mi[n]&&ma[n]<e) S2.insert(n);
}
val = min(val, DnC(s, mid, S1));
val = min(val, DnC(mid+1, e, S2));
return val;
}
signed main() {
cin.sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, K;
cin >> N >> K;
int i, j;
adj.resize(N);
for(i=0;i<N-1;i++) {
int a, b;
cin >> a >> b;
adj[a-1].push_back(b-1);
adj[b-1].push_back(a-1);
}
int l = 0;
vis[l] = true;
while(true) {
for(int n : adj[l]) {
if(!vis[n]) {
l = n;
break;
}
}
if(vis[l]) break;
vis[l] = true;
}
for(i=0;i<N;i++) vis[i] = false;
int cnt = 0;
while(cnt < N) {
A[cnt] = l;
cnt++;
vis[l] = true;
for(int n : adj[l]) {
if(!vis[n]) {
l = n;
break;
}
}
}
for(i=0;i<K;i++) {
ma[i] = -1;
mi[i] = N;
}
for(i=0;i<N;i++) {
cin >> C[i];
C[i]--;
B[A[i]] = C[i];
}
for(i=0;i<N;i++) {
ma[B[i]] = max(ma[B[i]], i);
mi[B[i]] = min(mi[B[i]], i);
}
for(i=0;i<K;i++) {
if(ma[i]==mi[i]) {
cout << "0";
return 0;
}
}
set<int> col;
for(i=0;i<K;i++) col.insert(i);
cout << DnC(0, N, col);
}
Compilation message
capital_city.cpp: In function 'int main()':
capital_city.cpp:62:12: warning: unused variable 'j' [-Wunused-variable]
62 | int i, j;
| ^
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
332 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
332 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
265 ms |
32340 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
332 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |