# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
570329 | Doxeno | Mergers (JOI19_mergers) | C++17 | 159 ms | 36948 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 500010;
vector<int> adj[MAXN];
vector<int> col[MAXN];
int c[MAXN];
int d[MAXN];
int st[MAXN][20];
bool vis[MAXN];
int mc[MAXN];
int og[MAXN];
int ans;
void dd(int n){
vis[n] = 1;
for(auto x: adj[n]){
if(vis[x])continue;
st[x][0] = n;
d[x] = d[n]+1;
dd(x);
}
for(int i = 1; i < 20; i++){
st[n][i] = st[st[n][i-1]][i-1];
}
}
int lca(int a, int b){
if(d[a] < d[b])swap(a,b);
for(int i = 0; i < 20; i++){
if((d[a]-d[b])&(1<<i))a = st[a][i];
}
for(int i = 19; i >= 0; i--){
if(st[a][i] != st[b][i]){
a = st[a][i];
b = st[b][i];
}
}
return st[a][0];
}
int dfs(int n){
vis[n] = 1;
int k = 0;
og[n] = mc[c[n]];
for(auto x: adj[n]){
if(vis[x])continue;
k+=dfs(x);
og[n] = min(og[n],og[x]);
}
if(og[n] == d[n] && k == 0){k = 1; ans++;}
return k;
//ans+=k;
//return(((n!=0) && (og[n] == d[n])) || (k&1));
}
int main(){
int N,K,a,b;
cin >> N >> K;
for(int i = 0; i < N-1; i++){
cin >> a >> b;
adj[--a].push_back(--b);
adj[b].push_back(a);
}
for(int i = 0; i < N; i++){
cin >> c[i]; c[i]--;
col[c[i]].push_back(i);
}
dd(0);
for(int i = 0; i < N; i++)vis[i] = 0;
for(int i = 0; i < K; i++){
if(col[i].empty())continue;
mc[i] = col[i][0];
for(int j = 1; j < col[i].size(); j++){
mc[i] = lca(mc[i],col[i][j]);
}
mc[i] = d[mc[i]];
}
dfs(0);
cout << (1+ans)/2 << endl;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |