#P5318. 【深基18.例3】查找文献

【深基18.例3】查找文献

Problem Description

Xiao K likes to browse Luogu blogs to gain knowledge. Each article may have several (or possibly none) reference links pointing to other blog articles. Xiao K is eager to learn: if he reads an article, he will definitely go read the references of this article (if he has already read a reference before, then he does not need to read it again).

Assume there are a total of n(1n105)n(1\le n\le10^5) articles in Luogu blogs (numbered from 11 to nn) and m(1m106)m(1\le m\le10^6) reference-citation relations. Currently, Xiao K has opened the article numbered 11. Please help Xiao K design a method so that he can read all the articles he can reach without repetition and without missing any.

Here is the organized reference-relation graph. In it, a reference XYX\to Y means article XX has reference YY. It is not guaranteed that article 11 is not cited by other articles.

Please perform DFS and BFS on this graph respectively, and output the traversal results. If there are multiple articles that can be visited, read the one with the smaller index first (so you may need to sort first).

Input Format

There are m+1m+1 lines in total. The first line contains two numbers, nn and mm, which indicate that there are n(1n105)n(1\le n\le10^5) articles in total (numbered from 11 to nn) and m(1m106)m(1\le m\le10^6) reference-citation relations.

In the next mm lines, each line contains two integers X,YX, Y, meaning that article XX has reference YY.

Output Format

There are 22 lines in total.

The first line is the DFS traversal result, and the second line is the BFS traversal result.

8 9
1 2
1 3
1 4
2 5
2 6
3 7
4 7
4 8
7 8
1 2 5 6 3 7 8 4 
1 2 3 4 5 6 7 8 

Hint

Translated by ChatGPT 5