比赛 |
20241022 |
评测结果 |
AAAAAAAAAAAAAAAAAAAA |
题目名称 |
猴猴吃苹果 |
最终得分 |
100 |
用户昵称 |
小金 |
运行时间 |
0.380 s |
代码语言 |
C++ |
内存使用 |
5.36 MiB |
提交时间 |
2024-10-22 11:53:24 |
显示代码纯文本
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=50010;
int n,root,tot,son[N],fa[N],top[N],size[N],dep[N],id[N],rk[N],head[N];
bool flag[N];
struct edge
{
int next,to;
}e[N*2];
struct Treenode
{
int l,r,maxn,pos,lazy;
};
struct Tree
{
Treenode tree[N*4];
int tot;
void pushup(int x)
{
if (tree[x*2].maxn>tree[x*2+1].maxn)
{
tree[x].maxn=tree[x*2].maxn;
tree[x].pos=tree[x*2].pos;
}
else if (tree[x*2].maxn<tree[x*2+1].maxn)
{
tree[x].maxn=tree[x*2+1].maxn;
tree[x].pos=tree[x*2+1].pos;
}
else if (tree[x*2].maxn==tree[x*2+1].maxn&&tree[x*2].pos<tree[x*2+1].pos)
{
tree[x].maxn=tree[x*2].maxn;
tree[x].pos=tree[x*2].pos;
}
else
{
tree[x].maxn=tree[x*2+1].maxn;
tree[x].pos=tree[x*2+1].pos;
}
}
void pushdown(int x)
{
if (tree[x].lazy)
{
tree[x*2].lazy+=tree[x].lazy;
tree[x*2+1].lazy+=tree[x].lazy;
tree[x*2].maxn+=tree[x].lazy;
tree[x*2+1].maxn+=tree[x].lazy;
tree[x].lazy=0;
}
}
void build(int x,int l,int r)
{
tree[x].l=l; tree[x].r=r;
if (l==r)
{
tree[x].maxn=dep[rk[l]];
tree[x].pos=rk[l];
return;
}
int mid=(l+r)>>1;
build(x*2,l,mid); build(x*2+1,mid+1,r);
pushup(x);
}
void update(int x,int l,int r)
{
if (tree[x].l==l && tree[x].r==r)
{
tree[x].lazy--;
tree[x].maxn--;
return;
}
pushdown(x);
int mid=(tree[x].l+tree[x].r)>>1;
if (r<=mid) update(x*2,l,r);
else if (l>mid) update(x*2+1,l,r);
else update(x*2,l,mid),update(x*2+1,mid+1,r);
pushup(x);
}
}Tree;
void add(int from,int to)
{
e[++tot].to=to;
e[tot].next=head[from];
head[from]=tot;
}
void dfs1(int x,int f)
{
dep[x]=dep[f]+1;
size[x]=1;
fa[x]=f;
for (int i=head[x];~i;i=e[i].next)
{
int v=e[i].to;
if (v!=f)
{
dfs1(v,x);
size[x]+=size[v];
if (size[v]>size[son[x]]) son[x]=v;
}
}
}
void dfs2(int x,int tp)
{
top[x]=tp;
id[x]=++tot;
rk[tot]=x;
for (int i=head[x];~i;i=e[i].next)
{
if(e[i].to==son[x]) dfs2(e[i].to,tp);
}
for (int i=head[x];~i;i=e[i].next)
{
int v=e[i].to;
if (v!=son[x] && v!=fa[x]) dfs2(v,v);
}
}
int main()
{
freopen("apple.in","r",stdin);
freopen("apple.out","w",stdout);
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&root);
root++;
for (int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
add(x+1,y+1);
add(y+1,x+1);
}
dep[0]=-1;
tot=0;
dfs1(root,0);
dfs2(root,root);
Tree.build(1,1,n);
printf("%d\n",root-1);
flag[root]=1;
while (Tree.tree[1].maxn)
{
int pos=Tree.tree[1].pos;
printf("%d\n",pos-1);
for(;!flag[pos];pos=fa[pos])
{
Tree.update(1,id[pos],id[pos]+size[pos]-1);
flag[pos]=1;
}
}
return 0;
}