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;
#define int long long
#define ii pair<int,int>
#define fi first
#define se second
#define endl '\n'
#define puf push_front
#define pof pop_front
#define pub push_back
#define pob pop_back
#define lb lower_bound
#define ub upper_bound
#define rep(x,s,e) for (int x=(s)-((s)>(e));x!=(e)-((s)>(e));((s)<(e)?x++:x--))
#define all(x) (x).begin(),(x).end()
#define sz(x) (int) (x).size()
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
struct UFDS{
int p[500005];
UFDS(){
rep(x,0,500005) p[x]=x;
}
int par(int i){
if (p[i]==i) return p[i];
else return p[i]=par(p[i]);
}
void unions(int i,int j){
i=par(i),j=par(j);
p[j]=i;
}
} ufds;
int n,k;
vector<int> al[500005];
vector<ii> edges;
vector<int> pos[500005];
int d[500005];
int pp[500005];
void dfs(int i,int p){
for (auto it:al[i]){
if (it==p) continue;
d[it]=d[i]+1;
pp[it]=i;
dfs(it,i);
}
}
int deg[500005];
signed main(){
cin>>n>>k;
int a,b;
rep(x,1,n){
cin>>a>>b;
al[a].pub(b);
al[b].pub(a);
edges.pub({a,b});
}
rep(x,1,n+1){
cin>>a;
pos[a].pub(x);
}
dfs(1,-1);
rep(x,1,k+1) rep(y,1,sz(pos[x])){
int a=pos[x][0],b=pos[x][y];
//cout<<a<<" "<<b<<endl;
while (a!=b){
if (d[a]<d[b]) swap(a,b);
ufds.unions(pp[a],a);
a=ufds.par(a);
}
}
for (auto [a,b]:edges){
a=ufds.par(a),b=ufds.par(b);
if (a!=b) deg[a]++,deg[b]++;
}
int ans=0;
rep(x,1,n+1) ans+=deg[x]==1;
cout<<(ans+1)/2<<endl;
}
# | 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... |