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;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rnd(int l,int r)
{
return l+rng()%(r-l+1);
}
#define fasty ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define forinc(x,a,b) for(int x=a;x<=b;x++)
#define fordec(x,a,b) for(int x=a;x>=b;x--)
#define fi first
#define se second
#define ii pair<int,int>
#define getbit(x,i) ((x>>(i))&1ll)
#define batbit(x,i) (x|(1ll<<(i)))
#define tatbit(x,i) (x&~(1ll<<(i)))
#define endl '\n'
//#define int long long
#define pb push_back
const int N = 5e5+10;
int n, k;
int a[N], l[N];
vector<int> ke[N];
vector<int> adj[N];
int P[N][20];
void dfs(int u, int pr)
{
forinc( i, 1,18 ) P[u][i] = P[P[u][i-1]][i-1];
for(auto v : ke[u])
{
if(v==pr) continue;
l[v] = l[u] + 1;
P[v][0] = u;
dfs(v,u);
}
}
int d[N];
queue<int> q;
void bfs()
{
while(!q.empty())
{
int u = q.front();
q.pop();
for(auto v : ke[u])
{
if(d[v] == -1)
{
d[v] = d[u] + 1;
q.push(v);
}
if(d[v] == d[u] + 1)
{
adj[v].pb(u);
}
}
}
}
bool cmp(int x, int y)
{
return l[x] > l[y];
}
int dd[N];
main()
{
// freopen("task.inp" , "r" , stdin);
fasty;
cin >> n >> k;
forinc(i,1,n-1)
{
int a,b;
cin >> a >> b;
ke[a].pb(b);
ke[b].pb(a);
}
dfs(1,0);
forinc(i,1,n) d[i]=-1;
forinc(i,1,k)
{
cin >> a[i];
d[a[i]]=0;
q.push(a[i]);
}
bfs();
sort(a+1, a+k + 1, cmp);
while(!q.empty()) q.pop();
vector<int> ans;
forinc(i,1,k)
{
if(dd[a[i]] ) continue;
int cur=a[i];
fordec(j,17,0)
{
int nxt = P[cur][j];
if(!nxt) continue;
if(l[a[i]] - l[nxt] <= d[nxt]) cur = nxt;
}
if(!dd[cur])
{
ans.pb(cur);
dd[cur]=1;
q.push(cur);
while(!q.empty())
{
int u = q.front();
q.pop();
for(auto v : adj[u])
{
if(!dd[v])
{
dd[v]=1;
q.push(v);
}
}
}
}
}
cout << ans.size() << "\n";
for(auto x : ans) cout << x << " ";
}
Compilation message (stderr)
pastiri.cpp:64:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
64 | main()
| ^~~~
# | 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... |