#3 RE 求hack
查看原帖
#3 RE 求hack
461452
SunLegend楼主2024/7/18 09:37
#include <bits/stdc++.h>
using namespace std;
int n,root[200005],marry[200005],x,tot,head[200005];
int ans,sum,size,ok,anss[200005];
struct Tree
{
	int rt,sons,rts;
}t[200005];
struct Edge
{
	int next,to;
}e[200005];
queue <int> q;
void dfs(int u)
{
	for(int i=head[u];~i;i=e[i].next)
	{
		size++;
		int v=e[i].to;
		dfs(v);
		if(!marry[v] && !marry[u]) 
		{
			marry[v]=1;
			marry[u]=1;
			sum++;
		}
	}
}
void qdfs(int u)
{
	if(!marry[u]) q.push(u),ok++;
	for(int i=head[u];~i;i=e[i].next)
	{
		int v=e[i].to;
		dfs(v);
	}
}
void addt(int rt)
{
	t[++x].rt=rt;
	sum=0;
	size=0;
	dfs(rt);
	t[x].sons=size-sum*2;
	t[x].rts=marry[rt];
	ans+=sum;
}
void adde(int from,int to)
{
	e[++tot].to=to;
	e[tot].next=head[from];
	head[from]=tot;
}
bool cmp(Tree xx,Tree yy)
{
	if(xx.sons) return 1;
}
int main()
{
	freopen("hidden.in","r",stdin);
	freopen("hidden.out","w",stdout);
	memset(head,-1,sizeof(head));
	scanf("%d",&n);
	for(int i=2;i<=n;i++)
	{
		scanf("%d",&x);
		if(x==0) root[i]=1;
		else adde(x,i),anss[i]=x;
	}
	x=0;
	root[1]=1;
	for(int i=1;i<=n;i++)
	{
		if(root[i])
		{
			addt(i);
			//cout<<t[x].rt<<' '<<t[x].sons<<' '<<t[x].rts<<endl;
		}
	}
	sort(t+1,x+t+1,cmp);
	for(int i=1;i<=x;i++)
	{
		if(q.size() && !t[i].rts)
		{
			ans++;
			anss[t[i].rt]=q.front();
			//cout<<q.front();
			q.pop();
		}
		//if(t[i].rts)
		qdfs(t[i].rt);
	}
	printf("%d\n",ans);
	for(int i=2;i<=n;i++)
	{
		if(!anss[i]) anss[i]=1;
		printf("%d ",anss[i]);
	}
	return 0;
} 
2024/7/18 09:37
加载中...