L2-3 龙龙送外卖---DFS+染色

#include
using namespace std;
const int N = 100010;
#define int long long
vector<int>g[N];
int father[N],depth[N];
bool col[N]={0};
void dfs(int u)
{
	for(auto v : g[u])
	{
		depth[v]=depth[u]+1;
		dfs(v);
	}
}
signed main()
{
	int n,m;cin>>n>>m;
	int root;
	for(int i=1,x;i<=n;i++)
	{
		cin>>x;
		if(x==-1)root=i;
		else g[x].push_back(i),father[i]=x;
	}
	dfs(root);
	int maxd=0,res=0;
	for(int i=0,x;i<m;i++)
	{
		cin>>x;
		maxd=max(maxd,depth[x]);
		while(x!=root&&!col[x])col[x]=true,x=father[x],res+=2;
		cout<<res-maxd<<'\n';
	}
} 

你可能感兴趣的:(比赛补题,深度优先,算法,c++)