E - Prerequisites 解説 by kyopro_friends


\(x\) を読むために本 \(y\) を読む必要があるとき、頂点 \(x\) から頂点 \(y\) への有向辺を張ったグラフにおいて、頂点 \(1\) からDFSしたときの帰りがけ順が答えになります。

#include<bits/stdc++.h>
using namespace std;

int main(){
	int n;
	cin >> n;
	vector<vector<int>>G(n+1);
	for(int i=1;i<=n;i++){
		int c;
		cin >> c;
		G[i].resize(c);
		for(auto&v:G[i])cin >> v;
	}

	vector<bool>visited(n+1);
	vector<int>ans;
	auto dfs=[&](auto self,int v)->void{
		for(auto vv:G[v])if(!visited[vv])self(self,vv);
		ans.push_back(v);
		visited[v]=true;
	};
	dfs(dfs,1);
	ans.pop_back();  // 1 自身は除く
	for(auto v:ans)cout << v << endl;
}

投稿日時:
最終更新: