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;
typedef pair<int,int> pii;
int n,K,par[500005];
int nr[500005],dp[21][500005],niv[500005],in[500005],out[500005],timp;
vector<int> muchii[500005];
vector<int> culs[500005];
int grad[500005];
map<pii,int> ban;
bool isancestor(int a,int b)
{
return in[a]<=in[b]&&out[a]>=out[b];
}
int LCA(int a,int b)
{
if(niv[a]>niv[b])
swap(a,b);
if(isancestor(a,b))
return a;
for(int i=20;i>=0;i--)
if(dp[i][a]!=0&&!isancestor(dp[i][a],b))
a=dp[i][a];
return par[a];
}
void initdfs(int nod)
{
timp++;
in[nod]=timp;
dp[0][nod]=par[nod];
for(int i=1;i<=20;i++)
dp[i][nod]=dp[i-1][dp[i-1][nod]];
for(int i:muchii[nod])
if(i!=par[nod])
{
par[i]=nod;
niv[i]=niv[nod]+1;
initdfs(i);
}
out[nod]=timp;
}
void calc(int nod)
{
for(int i:muchii[nod])
if(i!=par[nod])
{
calc(i);
nr[nod]+=nr[i];
}
if(nr[nod]==0&&nod!=1)
{
ban[{nod,par[nod]}]=1;
ban[{par[nod],nod}]=1;
}
}
int comp[500005],nrcomp;
void dfs(int nod)
{
comp[nod]=nrcomp;
for(int i:muchii[nod])
if(!comp[i])
if(ban.count({nod,i})==0)
dfs(i);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin>>n>>K;
for(int i=1;i<n;i++)
{
int a,b;
cin>>a>>b;
muchii[a].push_back(b);
muchii[b].push_back(a);
}
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
culs[x].push_back(i);
}
initdfs(1);
for(int i=1;i<=K;i++)
{
for(int j=1;j<culs[i].size();j++)
{
int a=culs[i][0];
int b=culs[i][j];
int lca=LCA(a,b);
nr[a]++;
nr[b]++;
nr[lca]-=2;
}
}
calc(1);
if(ban.empty())
{
cout<<0;
return 0;
}
for(int i=1;i<=n;i++)
if(!comp[i])
{
nrcomp++;
dfs(i);
}
for(auto z:ban)
{
pii p=z.first;
if(p.first>p.second)
continue;
int a=comp[p.first];
int b=comp[p.second];
grad[a]++;
grad[b]++;
}
int ans=0;
for(int i=1;i<=nrcomp;i++)
if(grad[i]==1)
ans++;
cout<<ans/2+ans%2;
return 0;
}
Compilation message (stderr)
mergers.cpp: In function 'int main()':
mergers.cpp:86:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
86 | for(int j=1;j<culs[i].size();j++)
| ~^~~~~~~~~~~~~~~
# | 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... |