This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//by szh
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pii pair<int,int>
#define pll pair<long long,long long>
#define pb push_back
#define debug(x) cerr<<#x<<"="<<x<<endl
#define pq priority_queue
#define inf 0x3f
#define rep(i,a,b) for (int i=a;i<(b);i++)
#define MP make_pair
#define SZ(x) (int(x.size()))
#define ll long long
#define mod 1000000007
#define ALL(x) x.begin(),x.end()
void inc(int &a,int b) {a=(a+b)%mod;}
void dec(int &a,int b) {a=(a-b+mod)%mod;}
int lowbit(int x) {return x&(-x);}
ll p0w(ll base,ll p) {ll ret=1;while(p>0){if (p%2ll==1ll) ret=ret*base%mod;base=base*base%mod;p/=2ll;}return ret;}
const int maxn = 5e5+10;
int n,m;
int dis[maxn];
bool vis[maxn];
int dep[maxn];
vector <int> sheep;
queue <int> q;
vector <int> edge[maxn];
vector <int> ans;
int a[maxn];
void bfs() {
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v:edge[u]) if (dis[v]>dis[u]+1) {
dis[v] = dis[u] + 1;
q.push(v);
}
}
return;
}
void dfs(int u,int fa) {
dep[u] = dep[fa]+1;
for (int v:edge[u]) {
if (v==fa) continue;
dfs(v,u);
}
}
void dfs1(int u,int fa,int mx,int opt) {
if (dep[u]+dis[u]>mx) {
mx = dep[u]+dis[u];
opt = u;
}
a[u] = opt;
for (int v:edge[u]) {
if (v==fa) continue;
dfs1(v,u,mx,opt);
}
}
void cover(int u) {
vis[u] = true;
for (int v:edge[u]) {
if (vis[v] or dis[v]+1!=dis[u]) continue;
cover(v);
}
}
int main() {
// freopen("input.txt","r",stdin);
std::ios::sync_with_stdio(false);cin.tie();
cin>>n>>m;
memset(dis,0x3f,sizeof(dis));
rep(i,1,n) {
int u,v;
cin>>u>>v;
edge[u].pb(v);
edge[v].pb(u);
}
rep(i,0,m) {
int x;
cin>>x;
sheep.pb(x);
q.push(x);
dis[x] = 0;
}
bfs();
dfs(1,0);
sort(ALL(sheep),[](const int lhs,const int rhs) {return dep[lhs]>dep[rhs];});
dfs1(1,0,0,0);
for (int it:sheep) {
if (vis[it]) continue;
cover(a[it]);
ans.pb(a[it]);
}
cout<<SZ(ans)<<"\n";
for (int it:ans) cout<<it<<" ";
return 0;
}
# | 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... |