题解 P8204【[Ynoi2005] tdnmo】
FunnyCreatress · · 题解
Top Cluster 板板题。
定义一棵树的簇 (cluster) 为树上的一个连通块,满足该连通块中至多有两个点与连通块外部相连,与外界相连的点称为界点。若一个簇存在两个界点,称这两点间的路径为该簇的簇路径。
Top Cluster 给出了一种将一棵
我们遍历整棵树,并同时维护一个栈,存储暂不属于任何一个簇的边。当遍历到某个节点时,我们依次遍历每个儿子,压入当前点到儿子的边,如果栈中在当前子树中的边超过了
这样划分出的簇大小显然是
关于此题,算是一个非常简单的应用。我们考虑一个类似于回滚莫队的做法。对于
话说我 THUPC 时写的那份东西好像有点问题,但是过了 下面这份东西应该是对的。
部分代码已删。
int n,m,B,fa[N],tp,qwq[N],b[N],ansc,dep[N],stp;vector<int> son[N];string ans;
struct qry{int x,y,id;};vector<qry> vq[N];
bool cmp(qry u,qry v){return dep[u.x]+u.y<dep[v.x]+v.y;}
pair<int,bool> dfs(int x){
int cntt=0,cnt=0;pair<int,bool> t;
for(int y:son[x])t=dfs(y),cntt+=t.second,cnt+=t.first;
if(cntt>=2||cnt>=B)qwq[x]=1,cnt=0;
return make_pair(cnt,cntt||qwq[x]);
}
void a1(int x,int y){ansc++,ans+="1 "+to_string(x)+" "+to_string(y)+"\n",stp++;}
void a2(){ansc++,ans+="2\n",stp--;}
void a3(int x){ansc++,ans+="3 "+to_string(x)+"\n";}
int main(){
scanf("%d%d",&n,&m);B=sqrt(n)+1;
for(int i=2;i<=n;i++)scanf("%d",&fa[i]),son[fa[i]].push_back(i),dep[i]=dep[fa[i]]+1;
dfs(1);
for(int i=1;i<=n;i++)if(qwq[i])
for(int j=i;j&&!b[j];j=fa[j])b[j]=i;
for(int i=1,x,y;i<=m;i++){
scanf("%d%d",&x,&y);
if(y==0)a3(i);
else if(!b[x])a1(x,y),a3(i),a2();
else vq[b[x]].push_back((qry){x,y,i});
}
for(int i=1;i<=n;i++)if(qwq[i]&&vq[i].size()){
sort(vq[i].begin(),vq[i].end(),cmp);while(stp)a2();
for(auto q:vq[i])a1(i,max(q.y+dep[q.x]-dep[i],0)),a1(q.x,q.y),a3(q.id),a2();
}
cout<<ansc<<'\n'<<ans;
return 0;
}