Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded.
Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.
A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds:
x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length);
in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively.
The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects.
Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.
Output
Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record.
Examples
Input
3 2
1 2
1 3
Output
1 2 3
Input
5 5
1 4
3 4
5 4
3 2
1 5
Output
1 4 3 2 5
Input
10 10
1 4
6 8
2 5
3 7
9 4
5 6
3 4
8 10
8 9
1 10
Output
1 4 3 7 9 8 6 5 2 10
Note
In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence {1, 2, 3}, which is the lexicographically smallest one.
In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence {1, 4, 3, 2, 5}, which is the lexicographically smallest one.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to find the lexicographically smallest permutation of nodes that can be recorded by a walk starting at node 1, visiting nodes (recording each new node when first visited) until all nodes are visited. The recorded sequence is the order of first visits. So essentially we want an ordering of nodes (starting with 1) such that there exists a walk that visits nodes in that order (first time) and then continues possibly revisiting. The walk can be any walk (repeating nodes and edges) as long as it's a valid traversal of edges.
This is reminiscent of the concept of "graph exploration" and "lexicographically minimum DFS order" or "Lexicographic Breadth-First Search"? But careful: The walk can be arbitrary; the only constraint is that when we want to visit a new node (next in sequence), we must be able to reach it from the current node via some path that may go through already visited nodes (since we can revisit). So the sequence a1=1, a2,..., an must satisfy that for each i>1, there exists a path from a_{i-1} to a_i using only nodes that have already been visited (or possibly not? Actually we need to go from a_{i-1} to a_i in the walk; we can traverse edges; we can go through nodes that may have been visited already or not. But when we go through a node that hasn't been recorded yet, we would record it on first encounter, which would change the order. So we must ensure that on the way from a_{i-1} to a_i, we don't accidentally encounter a new node before reaching a_i, because that would record it earlier and break the sequence. So the condition is: there must exist a path from a_{i-1} to a_i such that all intermediate nodes on that path (excluding the endpoints) are already visited (i.e., in {a_1,...,a_{i-1}}). Moreover, we might also consider if the path can include a_i itself? Obviously a_i is new, but it is the first time we visit it; it's okay that the endpoint is new. But any intermediate nodes must be already recorded. That's the standard condition for a "valid order" of a graph exploration with revisits allowed: we can only move to a new node by traversing a path that goes through already known nodes. This is exactly the condition that the order is a possible order of depth-first search (DFS) traversal? Actually DFS typically picks an unvisited neighbor and goes there, but can backtrack via visited nodes. That matches: starting from 1, each step you can go to an unvisited node via a path that may go through visited nodes; but if you go through visited nodes only, the first unvisited node encountered will be the one at the end of that path. So the sequence of first visits in any walk is exactly a "possible DFS order"? Not exactly; it's more general: you could at any point decide to go along any path of visited nodes to reach any unvisited node reachable through a visited subgraph. But the condition reduces to: The set of visited nodes at each step must be connected (since the graph is connected and we start with 1, and we only add nodes that are adjacent to some visited node via an edge that connects to the visited component? Wait, not exactly: if you have visited set S, you can only move within S (since you can only step on visited nodes without accidentally discovering new ones). From a node u in S, you can take an edge (u, v) where v is not in S. But if you take that edge, you'll immediately visit v, and that becomes the next recorded node. So the next new node must be adjacent (through a single edge) to some node in S? Because if you step from u (in S) along an edge to v (not in S), you discover v at that step. But what about taking a longer path that goes through unvisited nodes? If you step onto an unvisited node, you record it immediately, so you can't pass through an unvisited node without recording it. So indeed, to add a new node, you must step directly from a visited node to that node via a single edge. Because if the path includes any intermediate node that is not visited, that node would be visited first and become recorded earlier than intended. So the only way to first visit a node v is to step from some already visited node u to v directly along an edge (u, v). So the sequence must be such that for each i>1, there exists an edge between a_i and some node in {a_1,...,a_{i-1}}. But is that sufficient? Consider you're at a_{i-1} at the moment just before recording a_i. You need to move along a path that stays within visited nodes until the final step crossing the edge to a_i. Since you can only move on visited nodes, you need that there is a path from a_{i-1} to some neighbor u of a_i (which is visited) using only visited nodes, then take edge (u, a_i). The existence of an edge between a_i and some visited node is necessary but not sufficient if that visited node is not reachable from the current position using only visited nodes. However, since the visited set S is connected? Let's think: Starting from 1, after visiting a set S of nodes, can we guarantee that the subgraph induced by S is connected? Initially S={1} trivially connected. When we add a new node v via edge (u,v) where u in S, we can go from current position (some node in S) to u via a path within S (if S is connected), then step to v. So the condition for being able to add v from current position is that S is connected. Does our process maintain connectivity of S? Typically, after adding v, S becomes S ∪ {v}. Since v is adjacent to u, the new set is still connected. So as long as we start with connected S and always add a node adjacent to S, S remains connected. Also, we can move within S arbitrarily because S is connected; we can always find a path within S from any node to any other (since the induced subgraph may not be connected? Actually if the subgraph induced by S is not necessarily connected because we might have added nodes via edges but might have "holes"? Let's test: Suppose we have S = {1,2,3} with edges: 1-2, 2-3. That's connected. Good. Could there be a scenario where S is visited but the induced subgraph is not connected? How could we have visited a node that is not connected to 1 via visited nodes only? Initially we are at node 1. To visit a new node v, we must step from a visited node u to v via an edge (u,v). At the moment before stepping, we are at some node w (which is visited) and we can move within visited nodes. But we could, for example, start at 1, go to node 2 via edge (1,2) (new, record 2). Now S={1,2} and induced subgraph includes edge 1-2, so connected. Then from 2, we go to node 3 via edge (2,3) (new, record 3). S={1,2,3}, still connected. Then from 3, we could backtrack to 2 (visited) and then go to node 4 via edge (2,4) (new). That's fine: we moved from 3 to 2 within visited nodes (since 2 is visited), then step to 4. So after that S includes 4 which is adjacent to 2, so S remains connected because 4 connects via 2. So indeed S is always a connected subgraph (the visited nodes plus the edges we used to travel? Actually the connectivity of the induced subgraph: we need that any two visited nodes are connected by a path using only visited nodes. Is that always true? By induction, initial S={1} is connected. Suppose S is connected, and we add v via edge (u,v) where u in S. Then for any visited node x in S, we have path within S from x to u; then extend to v if needed. So S∪{v} is also connected. So visited set remains connected at all times. Moreover, we can always move from the current node to any other visited node via a path within S because S is connected. So the condition reduces to: The sequence must start with 1, and each subsequent node a_i must be adjacent (i.e., have an edge) to at least one node that appears earlier in the sequence. That's it? Let's double-check: After visiting a set S, we are at some node p (the last recorded node). To record a new node v, we need to move from p to some neighbor u of v (u in S) via a path in S, then traverse edge (u,v). Since S is connected, such a path exists from p to u within S. So yes, as long as v has at least one neighbor in S, we can do it. But is there any nuance about multiple edges or self-loops? Self-loops: edge (u,u). That wouldn't help because to visit a new node v, need edge from a visited node to v. So self-loops are irrelevant. Multiple edges are fine; they just provide more possibilities.
Thus the problem becomes: Given a connected undirected graph, find a permutation (starting with 1) that is lexicographically smallest among all permutations such that for each i>1, there exists j < i with edge (a_i, a_j). In other words, an ordering of vertices that is a "spanning tree order" where each vertex (except the first) is adjacent to some earlier vertex. This is exactly the definition of a sequence that can be produced by a DFS (or any graph search that adds vertices one by one from the frontier). This is also equivalent to ordering the vertices according to a breadth-first search? Not exactly: BFS also satisfies that each vertex is adjacent to some earlier vertex (its parent). However, the order in BFS is determined by levels; it might not be lexicographically minimal. For lexicographically minimal permutation under this adjacency constraint, we want to pick the smallest possible next vertex that can be added given the current visited set. Since lexicographic order compares sequences element by element, to minimize the sequence we want a_2 as small as possible, then a_3 as small as possible given the previous choices, etc.
So we can think of a greedy algorithm: maintain the visited set S (initially {1}). At each step, we need to choose the smallest vertex not yet visited that is adjacent to S (i.e., has at least one neighbor in S), and then add it to S. This seems plausible. But is it always optimal? This is reminiscent of the "lexicographically smallest BFS/DFS" or "minimum labeling order" problem known as "Lexicographic Breadth-First Search (LexBFS)" but that is different. Here we are free to choose any order as long as each new vertex connects to visited set. The greedy choice of always picking the smallest eligible vertex yields a sequence known as the "minimum spanning tree order" or "Prim's algorithm order" if we consider edges? Actually Prim's algorithm for MST picks the smallest edge connecting the tree to an outside vertex, not the smallest vertex. But if we pick smallest vertex adjacent to visited set, does that guarantee the existence of a walk that respects the order? We argued that as long as each new vertex is adjacent to visited set, we can extend. And we can always ensure we are at the appropriate neighbor when needed: When we want to add vertex v (smallest eligible), we need to actually move from current node p to some neighbor u of v within visited set, then step to v. Since S is connected, we can plan a path. But is there any conflict because after adding v we may need to later add even smaller vertices that become eligible later? But by definition, we always pick the smallest vertex among all unvisited that are adjacent to S at that moment. However, could there be a scenario where by picking a slightly larger vertex now, we enable a smaller vertex to become adjacent earlier? But "adjacent to S" is monotonic: As S grows, the set of vertices adjacent to S can only increase (or stay same). So if a vertex is not adjacent to S now, it might become adjacent later after adding some vertices. However, we want the lexicographically smallest sequence. At position i, we need to choose the smallest possible a_i given the prefix so far. The prefix determines S (the set of visited vertices). After fixing a prefix, the next vertex must be adjacent to S. The lexicographically smallest global sequence can be obtained by a greedy algorithm: At each step, choose the smallest vertex that can appear next, i.e., the smallest vertex not in S that is adjacent to S. Is that always globally optimal? Typically, for problems of lexicographically minimal sequence where constraints are monotone (the set of allowed choices expands as you add more elements), greedy works. But we need to check if there is any subtlety: Could picking a slightly larger vertex now allow us to have a smaller vertex later at an earlier position? No, because later positions are after current; the order is fixed; earlier positions dominate lexicographic comparison. So to minimize the sequence, we must minimize a_2 as much as possible; then given that, minimize a_3, etc. So at step i, we need to consider: Among all possible completions (sequences that satisfy constraints) with the given prefix, what is the minimal possible a_i? If we can prove that the smallest vertex adjacent to S is always achievable as the next element in some valid completion, then greedy works.
But is the smallest adjacent vertex always achievable? We must ensure that after adding that vertex v, we can still eventually visit all vertices (i.e., complete to a full permutation) while respecting the rule that each new vertex is adjacent to the visited set at the time of addition. Since the graph is connected, there is always some spanning tree. If we add v now, we can later add any other vertices because the visited set remains connected and the graph is connected; but is it possible that by adding v (the smallest adjacent), we block the ability to later add some other vertex? The visited set only grows; it never shrinks. Adding vertices only increases the frontier. So if later some vertex w is not yet visited, and the graph is connected, there will be some path from the visited set to w. However, the path may go through unvisited vertices; but we need to add w by stepping from a visited vertex to w directly via an edge. But if w is not adjacent to the visited set at that later time, can we make it adjacent by first visiting some other vertices that connect it? Yes, we can add intermediate vertices that become adjacent, eventually making w adjacent. So as long as the overall graph is connected, we can eventually visit all vertices from any growing visited set, by repeatedly adding vertices adjacent to the current set. This is similar to building a spanning tree: we can always extend the visited set to cover all vertices by adding any adjacent vertex. So picking the smallest adjacent vertex at each step should never prevent completion because we can always continue with the remaining vertices by adding them in some order (e.g., via a BFS from current set). So greedy is feasible.
Thus the problem reduces to: Starting with visited set S = {1}, repeatedly select the smallest vertex not in S that has at least one neighbor in S, add it to S, and output it. This yields the lexicographically smallest sequence.
But wait: Is there any possibility that the smallest vertex adjacent to S is not reachable from the current node without passing through unvisited vertices? We argued that we can always move within S to any node in S, because S is connected. Initially S={1} is trivially connected. After adding v via edge (u,v) where u∈S, S∪{v} remains connected because v is adjacent to u. So S stays connected throughout. Thus from the current node (which is some node in S, maybe the previously added vertex) we can travel within S to u, then step to v. So feasible.
Therefore, the greedy algorithm is correct.
Now we need to implement efficiently for n,m up to 1e5.
We maintain a boolean array visited (size n+1). Initially visited[1]=true. We maintain a min-heap (priority queue) of candidate vertices that are adjacent to the visited set but not yet visited. However, a vertex might become adjacent multiple times; we need to avoid duplicates. Standard approach: use a priority queue of unvisited vertices that are adjacent to visited set. When we mark a vertex as visited, we examine its neighbors; for each neighbor that is not visited, we add it to the priority queue (if not already present? But duplicates are okay as long as we check visited when popping). But careful: The condition for being a candidate is that the vertex has at least one neighbor visited. So when we visit a new vertex u, all its unvisited neighbors become eligible (since they now have a visited neighbor: u). However, a vertex might already be in the priority queue from previous visited neighbors. That's okay; we can push it again. When we pop from the min-heap, if the popped vertex is already visited, we skip. We continue until we have visited all n vertices.
But is it sufficient to only consider neighbors of newly visited vertices? Initially, only node 1 is visited. So we push all neighbors of 1 into the heap (since they become eligible). Then we pop the smallest unvisited neighbor, mark it visited, and then push its unvisited neighbors. This process is similar to Prim's algorithm for MST, but using vertex labels as weights rather than edge weights. Indeed, this is exactly like building a spanning tree where we choose the smallest vertex adjacent to the current set.
However, we must consider that after we pop a vertex v from heap, it's the smallest among all candidates. But could there be a vertex that becomes eligible later that is smaller than the current smallest candidate? For instance, suppose we have visited set S, and there is a vertex x not yet visited and not adjacent to S, but later after we add some vertices, x becomes adjacent. At that moment, x might be smaller than some candidates currently in the heap. But that's okay because when we pop from the heap, we always get the smallest among those currently eligible. If x becomes eligible later, it will be pushed into the heap then. Since we are processing in order, we might have already popped larger vertices before x becomes eligible. But is it possible that by waiting (i.e., not popping the current smallest candidate) we could eventually get an even smaller candidate? No, because if x is not eligible now, then we cannot add it now. We must add some vertex now to progress. The only vertices we can add now are those currently eligible. Among them, we want the smallest possible to minimize the sequence. Even if later a smaller vertex becomes eligible, it would be added later, which is after the current step, so it wouldn't affect the current position in the sequence. So we must pick the smallest among currently eligible vertices. So popping the min from heap at each step is correct.
Thus algorithm: BFS/DFS-like expansion with a priority queue.
Complexities: O((n+m) log n) due to heap operations.
Now confirm with examples:
Example 1:
n=3, edges:1-2,1-3.
Start visited {1}. heap neighbors: 2,3. Pop min 2, output 2. Add neighbors of 2: neighbor 1 visited, so none new. Heap now contains 3 (maybe duplicate but okay). Pop 3, output 3. Sequence: 1,2,3. matches.
Example 2:
n=5, edges: 1-4,3-4,5-4,3-2,1-5.
Start visited {1}. neighbors of 1: 4,5. heap:4,5. Pop min 4, output 4. neighbors of 4: 1 visited,3,5. Add unvisited: 3. heap now:5,3. Pop min 3, output 3. neighbors of 3: 4 visited,2. Add 2. heap:5,2. Pop min 2, output 2. neighbors of 2: 3 visited, no new. heap:5. Pop 5, output 5. Sequence:1,4,3,2,5. matches.
Example 3:
n=10, edges: (list) ... Output given: 1 4 3 7 9 8 6 5 2 10.
Let's simulate quickly: Start with 1 visited. Neighbors of 1 from edges: 4,10. heap:4,10. Pop min 4, output 4.
Neighbors of 4: from edges:1,9,3. Add unvisited:9,3. heap now:10,9,3 (since 10 still there). Pop min 3, output 3.
Neighbors of 3: from edges:7,4,? edges: 3 7, 3 4. Add unvisited:7. heap:10,9,7. Pop min 7, output 7.
Neighbors of 7: from edges:3 (visited), none else? edges: 3 7 only? Also maybe others? Input edges: (3,7) present. So only neighbor 3. No new. heap:10,9. Pop min 9, output 9.
Neighbors of 9: edges: 4,8? Input: 9 4, 8 9. So neighbors: 4 visited, 8 unvisited. Add 8. heap:10,8. Pop min 8, output 8.
Neighbors of 8: edges: 6,10,9? Input: 6 8, 8 10, 8 9. So neighbors:6,10,9. Add unvisited:6,10. heap:10 (already),6,10 (duplicate). So heap contains 10,6,10. Pop min 6, output 6.
Neighbors of 6: edges: 5,8? Input: 5 6, 6 8. neighbors:5,8. Add unvisited:5. heap:10,10,5. Pop min 5, output 5.
Neighbors of 5: edges: 2,6,4? Input: 2 5, 5 6, 5 4? Actually edge list: 2 5 is present, 5 6 present, 5 4? Wait there is edge 5 4? Yes "5 4" is there. So neighbors:2,6,4. Add unvisited:2. heap:10,10,2. Pop min 2, output 2.
Neighbors of 2: edges: 5 visited, maybe other? Only 5. No new. heap:10,10. Pop min 10, output 10. Done. Sequence:1,4,3,7,9,8,6,5,2,10. matches example. Good.
Thus algorithm works.
But wait: The problem statement says the graph may have multiple edges and self-loops. Self-loops are irrelevant; multiple edges might cause duplicate neighbor entries, but that's fine; our algorithm may push the same neighbor multiple times due to multiple edges, but visited check avoids duplication.
Edge Cases: Graph with n=1. Then sequence is just 1. No edges needed. Our algorithm: visited[1]=true; neighbors of 1: none, heap empty, but we still need to output only 1. That's fine; we can just output 1 initially then loop while visited count < n, but if heap empty and visited count < n, that would be problem, but in a connected graph with n>1 there will be edges. With n=1, visited count already 1, loop not entered. Works.
Now complexity: We'll iterate over each edge twice (once for each endpoint when its endpoint is visited) to push neighbors. Each push is O(log n). So O((n+m) log n). With n,m up to 1e5, fine.
Memory: adjacency list.
Implementation details:
Use 1-indexing.
visited array of bool or int.
Use priority_queue (min-heap) in C++: by default max-heap, so we can use greater or store negative.
Alternatively use set? But heap is simpler.
But careful: We need to ensure we don't push already visited neighbors; we check if !visited[neighbor] before pushing.
Potential issue: When we pop from heap, we might get a vertex that is already visited because it could have been pushed multiple times before being visited. So we must check visited flag and skip if already visited.
Pseudo:
int n,m;
vector<vector> adj(n+1);
read input;
visited[1] = true;
count = 1;
output sequence: cout << 1;
priority_queue<int, vector, greater> pq; // min-heap
for each neighbor v of 1:
if (!visited[v]) pq.push(v);
while (count < n) {
int u = pq.top(); pq.pop();
if (visited[u]) continue;
visited[u] = true;
count++;
cout << " " << u;
for each neighbor v of u:
if (!visited[v]) pq.push(v);
}
That's it.
But is there any scenario where the heap becomes empty before all vertices visited? In a connected graph, eventually all vertices become reachable; but our process: we only push neighbors of visited vertices. Since the graph is connected, every vertex is adjacent to some visited vertex at the time its neighbor becomes visited. However, if we start with 1, we push its neighbors. Then we pop and visit them. This process essentially expands the visited set. Since the graph is connected, eventually all vertices will be added to the heap (or visited) because each vertex will have at least one neighbor that becomes visited before it is visited (since we can order vertices along any spanning tree). More formally, by induction, the set of vertices that have been pushed into the heap at some point includes all vertices adjacent to visited set. As visited set expands, eventually all vertices become adjacent and thus pushed. So heap won't be empty until all visited. However, if we pop in a way that we skip visited ones, we might drain the heap temporarily if we don't push new candidates before popping all. But we push new candidates when we visit a vertex. So the while loop will always eventually have a candidate. For example, consider a chain 1-2-3. Start: visited {1}, push neighbor 2. heap={2}. pop 2, visit, push neighbor 3. heap now has {3} (after pushing). So okay.
Thus algorithm is correct.
Now we must produce output as space-separated.
But is there any nuance? Let's double-check the condition: The recorded sequence is the order of first visits during a walk. We argued that a necessary and sufficient condition is that each new vertex is adjacent to some previously visited vertex. Is that indeed sufficient? We need to demonstrate that we can actually perform the walk to realize that order. Given order a1=1, a2,...,an such that for each i>1, there is an edge between a_i and some a_j with j<i. We need to construct a walk that first visits a1, then a2, etc., without accidentally visiting other new vertices earlier. The constructive walk: start at a1. For i from 2 to n: Since the visited set S_{i-1} = {a1,...,a_{i-1}} is connected? Actually is it necessarily connected? We need to ensure we can move from the current position (which is a_{i-1} after visiting it) to some neighbor u of a_i that is in S_{i-1}, via a path within S_{i-1}. This requires that the induced subgraph on S_{i-1} is connected. Is it guaranteed by the condition that each a_i is adjacent to some earlier? Not necessarily. Consider a graph: nodes 1,2,3 with edges: 1-2, 1-3. The order 1,2,3 works because S={1,2} is connected? After visiting 1 and 2, S={1,2} includes edge 1-2, so connected. That's fine. But can we create an order where S_{i-1} is not connected? Suppose we have a graph: triangle 1-2-3-1. Order: 1,2,3 is fine. Could we have order: 1,3,2? After 1 and 3, S={1,3}; but there is edge 1-3? In triangle there is edge 1-3, so S is connected. Actually if the graph has edge between 1 and 3. To have S not connected, we would need a situation where the set of visited vertices is not connected because there is no edge between some pairs. But is that possible under the condition that each new vertex is adjacent to some earlier? Let's try: Graph: 1 connected to 2 and 3, but 2 and 3 not directly connected. Order: 1,2,3: After 1 and 2, S={1,2} with edge 1-2, connected. Then add 3 via edge 1-3, which is okay. So S stays connected because each new vertex connects to at least one existing node; but if that existing node is part of a connected component, adding it keeps connectivity. However, is it possible that after adding several vertices, the visited set becomes disconnected? Suppose we have visited set S that is connected. We add vertex v that is adjacent to some u in S. Then S∪{v} remains connected because v is linked to u. So if we start with a connected set (just {1}), and each addition connects to the set, the visited set remains connected. So by induction, S_{i} is always connected. This relies on the fact that at the time we add a_i, we are adding it to S_{i-1} which is connected. So the condition is sufficient to maintain connectivity. Therefore, the order ensures S_{i-1} is connected for all i. So we can always move from a_{i-1} to any u in S_{i-1} via a path within S_{i-1}. So we can go from a_{i-1} to the neighbor u (which is in S_{i-1}) then step to a_i. So the order is realizable.
Thus the greedy algorithm yields a valid order.
Therefore answer: simulate as described.
But wait: The problem statement says: "Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded." So the recorded permutation is the order of first visits. Our interpretation matches.
Now, could there be any possibility that the lexicographically smallest sequence is not achievable by this simple greedy? Let's test with some tricky cases, like graph with many edges and maybe some vertices only reachable via others. For greedy to fail, there must be a scenario where picking the smallest eligible vertex now leads to a situation where later we are forced to have a larger vertex earlier than if we had picked a slightly larger vertex now, which would allow an even smaller vertex to become eligible earlier? But the lexicographic comparison is fixed: we compare a_2 first; if we pick a larger a_2, the sequence is already larger regardless of later. So we must minimize a_2 as much as possible. So we must pick the smallest possible a_2 among all completions. That smallest possible is indeed the smallest vertex adjacent to 1 (since a_2 must be adjacent to some earlier node, which at that point is only 1). So a_2 is min(neighbors of 1). That's what greedy does. For a_3, given we have visited {1, a_2}, we need to choose the smallest vertex not visited that is adjacent to either 1 or a_2. The greedy picks exactly that. However, could there be a different choice for a_2 that would yield a smaller a_3 even though a_2 itself is larger? No, because a_2 is compared first; if a_2 is larger, the sequence is already larger even if a_3 is 1. So no trade-off. So greedy is optimal. This reasoning holds inductively.
Thus solution is correct.
Now complexity O((n+m) log n). For n,m up to 1e5 it's fine.
But we must be careful about memory and speed. Use fast I/O.
Edge Cases: Graph with multiple edges and self-loops. Self-loops (u,u) will cause neighbor u to be considered; but when we process neighbor v = u, visited[u] is true if u is visited; if not visited, pushing self-loop might allow a vertex to be considered as neighbor of itself? But a self-loop doesn't connect to a different vertex; if we are at u and we traverse a self-loop, we stay at u. So it does not help to visit a new vertex. So we can ignore self-loops or they won't affect because if u is not visited, we might push u into heap via self-loop? For example, from visited node u? Actually if we have a self-loop on a node v that is not visited, and we process a neighbor list of some visited node w, self-loop on v only appears if w=v? No, self-loop is only incident to v itself. So when we process neighbors of visited node w, we will only see v as neighbor if there is edge (w,v). Self-loop (v,v) will be seen only when w=v (i.e., when v is visited). At that time, we'll see neighbor v which is already visited, so skip. So self-loop won't cause any unvisited node to be added. So fine.
Multiple edges: may cause duplicate pushes; visited check handles.
Thus answer.
Now we should produce the code.
But wait, there's an alternative interpretation: The walk might not require that the new node is directly adjacent; maybe you could "jump" through unvisited nodes if you don't record them because you might traverse an edge to an unvisited node but not "visit" it? The problem says: "Whenever he visits a node not recorded on his notebook, he records it." So as soon as he arrives at a node (steps onto it), he checks his notebook; if not recorded, he records it. So you cannot pass through an unvisited node without recording it because you necessarily visit it when you step onto it. So yes, you must record immediately. So the only way to have a new node recorded as a_i is that the step from a visited node to that node is directly along an edge.
Thus our condition stands.
Now I'm thinking about whether the visited set remains connected given the walk? We argued yes because we always add a vertex adjacent to the current visited set. But is it possible that during the walk, after adding a new vertex, we might not be at that vertex? The sequence is the order of first visits. The walk might involve moving around after visiting a node before visiting the next new one. But we only care about the order of first visits; we can design the walk to satisfy being at the appropriate node before the next addition. In our constructive walk: after visiting a_i, we will stay within visited set and move to some neighbor u of a_{i+1} then step to a_{i+1}. Since visited set is connected, we can always do that. So the connectivity of visited set ensures realizability.
Now, is there any possibility that the greedy algorithm could get stuck? Not in a connected graph. Because at any point, there is at least one unvisited vertex, and since the graph is connected, there is a path from visited set to that vertex. The first edge on that path from visited set to an unvisited vertex is an edge between a visited vertex and an unvisited vertex, making that unvisited vertex eligible. So the set of eligible vertices is nonempty. So the heap will not be empty.
Thus solution.
Now we need to implement.
But wait, could there be any nuance about lexicographic ordering when the sequence length is fixed? The definition says: "x is lexicographically smaller than y if ... x is a prefix of y, but x≠y (this is impossible in this problem as all considered sequences have the same length)". So we only care about element-wise comparison.
Thus final answer.
Now we can code.
Let's test with a custom case: chain 1-5-2-3-4. Nodes 1 connected to 5, 5 connected to 2, 2 connected to 3, 3 connected to 4. According to greedy: start 1, neighbors: 5. heap {5}, pop 5, output 5. neighbors of 5: 1 visited,2 unvisited -> push 2. heap {2}. pop 2, output 2. neighbors of 2:5 visited,3 unvisited -> push 3. heap {3}. pop 3, output 3. neighbors of 3:2 visited,4 unvisited -> push 4. heap {4}. pop 4, output 4. Sequence: 1,5,2,3,4. Is that lexicographically smallest? Let's check other possible sequences. Could we get 1,2,...? To get 2 as second, we need edge from 1 to 2, but there is none (only 1-5). So impossible. Could we get 1,3? Need edge 1-3, no. 1,4? no. So second must be 5. So 1,5,... Next, after {1,5}, eligible vertices are neighbors of 1 or 5: neighbors of 1: 5 visited; neighbors of 5: 2. So only 2. So third must be 2. Then 3, then 4. So the only possible sequence is 1,5,2,3,4. So greedy gives the only one, which is smallest. Good.
Another case: star graph: 1 connected to all others. Then greedy: neighbors of 1 sorted: 2,3,4,...,n. So sequence 1,2,3,...,n. Is that lexicographically smallest? Yes because a_2 must be smallest neighbor, which is 2. After {1,2}, eligible: all other neighbors still adjacent to 1, so smallest is 3, etc. So correct.
Now a more complex graph: Suppose 1 connected to 2 and 3. 2 connected to 4. 3 connected to 4. Greedy: start {1}, neighbors: 2,3 -> pick 2. Then visited {1,2}, eligible: neighbors of 1 and 2: 3 (from 1) and 4 (from 2). Smallest is 3. Then visited {1,2,3}, eligible: neighbors: 4 (adjacent to 2 or 3). So sequence: 1,2,3,4. Could there be sequence 1,3,2,4? That is lexicographically larger because at second position 3 > 2. So greedy gives smaller. Indeed 1,2,3,4 is smaller.
Now consider graph where 1 connects to 2 and 4, and 2 connects to 3, and 4 connects to 3. Greedy: neighbors of 1: 2,4 -> pick 2. Then eligible: from {1,2}: neighbors: 4 (from1), 3 (from2). Smallest is 3? Actually 3 vs 4: 3 is smaller. So pick 3. Then visited {1,2,3}, eligible: neighbors: 4 (adjacent to 1 or 3). So sequence: 1,2,3,4. Could we get 1,2,4,3? That would be lexicographically larger at third element (4 vs 3). So greedy good.
Now consider a graph where 1 connects to 2 and 5; 2 connects to 3; 5 connects to 3; 3 connects to 4. Greedy: start: neighbors of 1: 2,5 -> pick 2. Then visited {1,2}, eligible: neighbors: 5 (from1), 3 (from2). smallest is 3 (since 3<5). So pick 3. Then visited {1,2,3}, eligible: neighbors: 5 (from1), 4 (from3). smallest is 4? 4 <5, so pick 4. Then visited {1,2,3,4}, eligible: 5 (from1). So sequence: 1,2,3,4,5. Lexicographically smallest? Could we get 1,2,5,3,4? At third element, 5 > 3, so larger. Could we get 1,5,2,3,4? At second element, 5 > 2, larger. So fine.
Now consider a graph where 1 connects to 2 and 3, and 2 connects to 4, 3 connects to 4. Greedy gave 1,2,3,4. Could there be a scenario where picking 2 first leads to a later forced larger element, whereas picking 3 first could lead to a smaller later element? No because second element is compared first. So no.
Thus greedy stands.
Now, is there any nuance about the requirement that the walk must be continuous? For instance, after visiting all nodes, we stop. The walk can be arbitrarily long, but we only care about the order of first visits. So as long as we can schedule first visits in the given order, it's fine. Our constructive walk: start at a1. For i from 2 to n: travel from current node (a_{i-1}) to some neighbor u of a_i via a path within visited set (possible because visited set is connected), then step to a_i. This yields a valid walk. So the order is realizable.
Thus the problem reduces to the described greedy.
Now, we should also consider if there could be a lexicographically smaller sequence that does not follow the greedy selection because maybe a_i is not adjacent to S_{i-1}? That's impossible by necessity. So all sequences must satisfy adjacency condition. So greedy yields minimal among those sequences.
Now, we must output the permutation. Implementation straightforward.
But wait, there is a known problem: "Lexicographically smallest DFS order" is different: In DFS, you go deep, but here we can "teleport" within visited set, so it's more like a "lexicographically smallest order of vertex addition to a connected set". That is exactly the result of repeatedly taking the smallest vertex adjacent to the current connected component.
Thus code is done.
Let's consider performance: Using adjacency list, pushing all neighbors of each visited node. That might push many duplicates due to multiple edges, but total pushes O(m) times per visited node? Actually each edge (u,v) will cause pushes when u is visited and v is unvisited: then push v. And when v is visited and u is unvisited: then push u. So at most 2*m pushes. But careful: if both u and v are visited, no push. So total pushes O(m). However, if there are multiple edges between same pair, each edge will cause a push when one endpoint is visited and the other is not. For example, two edges between 1 and 2: when 1 visited, we will push 2 twice (duplicate). That's okay; each push is O(log n). So total O(m log n). With m up to 1e5, fine.
Memory: adjacency list storing each edge twice (undirected) so O(m).
Implementation details: Use vector adj[n+1]; For each edge (u,v), push v to adj[u] and u to adj[v] if u!=v. For self-loop, we could ignore or push both; but if u==v, pushing u to adj[u] would create a self-loop; when visited, it will see neighbor u (itself) and skip because visited, so it's harmless but consumes push maybe? When u is visited and we see neighbor u, we will check !visited[u] which is false, so we won't push. So self-loop doesn't cause any push. So we can include them; but to avoid unnecessary storage, we can skip self-loops. But it's okay.
Thus code.
Now I should produce final answer.
But before finalizing, let's double-check the problem statement: It says "connected graph" but allows self-loops and multiple edges. Graph being "connected" likely means that ignoring self-loops and multiple edges, the underlying simple graph is connected? Usually connectivity definition for graphs with loops and parallel edges: a loop doesn't affect connectivity, and multiple edges are just extra. So it's fine.
Now, also note that n and m are up to 1e5, so using recursion may cause stack overflow if we implement DFS recursively, but we are not using recursion.
Implementation:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<vector> adj(n+1);
for (int i=0; i<m; i++) {
int u, v;
cin >> u >> v;
if (u == v) continue; // skip self-loops; optional
adj[u].push_back(v);
adj[v].push_back(u);
}
vector visited(n+1, false);
visited[1] = true;
priority_queue<int, vector, greater> pq;
for (int v : adj[1]) {
if (!visited[v]) {
pq.push(v);
}
}
vector order;
order.push_back(1);
while (order.size() < n) {
int u = pq.top();
pq.pop();
if (visited[u]) continue;
visited[u] = true;
order.push_back(u);
for (int v : adj[u]) {
if (!visited[v]) {
pq.push(v);
}
}
}
for (int i=0; i<n; i++) {
cout << order[i] << " \n"[i==n-1];
}
return 0;
}
Test on given examples.
Let's test manually.
Example 1:
n=3,m=2 edges:1-2,1-3.
adj[1]=[2,3], adj[2]=[1], adj[3]=[1].
visited[1]=true; push 2 and 3. order=[1]; pq top=2, pop, visited[2]=true, order=[1,2]; push neighbors of 2:1 visited skip; pq now [3]; pop 3; order=[1,2,3]. Output "1 2 3". Good.
Example 2: Already tested.
Example 3: Already tested.
Now, check edge case n=1: No edges. adj[1] empty; order=[1]; while loop condition order.size()<n (1<1 false). Output "1". Good.
Now, test a case with multiple edges: n=2, m=3 edges: 1-2,1-2,2-2 (self-loop). Our code skips self-loop? We skip only if u==v; so we skip the self-loop. Then adj[1]=[2,2] (two entries), adj[2]=[1,1] (two entries). visited[1]=true; for each neighbor of 1: push 2 twice. pq contains two 2s. Then order size=1<2; pop top=2, visited[2]=true, order push 2, then push neighbors of 2: 1 visited skip (both). Then pop next top (still 2) but visited so skip; order size becomes 2, loop exits. Output "1 2". Good.
Now, if we didn't skip self-loop, we would push nothing extra. Fine.
Now, what about large n,m? Should be fine.
Thus solution accepted.
Now, I'm thinking: Could there be any scenario where the greedy picks a vertex that is not the smallest eligible due to duplicates? No.
Thus final answer.
However, let me reflect: The reasoning about connectivity of visited set: We assumed that at each step, visited set is connected because we always add a vertex adjacent to it. But is it guaranteed that we can always move from the current node (the last added) to any other visited node? Yes, because visited set is connected, there exists a path; but we need to actually traverse that path without accidentally discovering new nodes. Since we only traverse visited nodes, it's safe. So indeed the order is realizable.
Now, is there any alternative order that also satisfies the adjacency condition but is lexicographically smaller than the greedy order? No, because at each step greedy picks the smallest possible among those that are eligible; any different order would have a larger element at the first position where they differ. So it's optimal.
Thus solution final.
Now, as a further check, I'll try to see if there is any subtle condition about the walk being "wandering" meaning Bob can wander arbitrarily, but maybe he can also decide to not record a node if it's already recorded, but that's fine.
Thus answer.
Now I can produce final solution.
One more nuance: The problem statement says: "Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it." It implies that at the start, he records node 1 because he is there. Then he wanders; when he moves to another node, if it's not recorded, he records it. So the sequence includes the starting node. So correct.
Now, I'm thinking: Is it possible to record a sequence that does not satisfy the adjacency condition? Suppose we have nodes 1-2-3, with edges 1-2 and 2-3. Could we record the order 1,3,2? Starting at 1. To record 3 before 2, we need to get to 3 without visiting 2. But the only path from 1 to 3 goes through 2. If we go along the path 1->2->3, then when we step onto 2 (unrecorded), we would record it, so 2 would be recorded before 3. So impossible. So indeed adjacency condition necessary.
Thus correct.
Now, what about using a different route that goes through a cycle and maybe revisit nodes to avoid stepping on unrecorded node? For example, graph: 1 connected to 2, 2 connected to 3 and 4, 3 connected to 4. Could we record 1,4,3,2? Starting at 1. To record 4 first after 1, we need to go from 1 to 4 without stepping on unrecorded nodes. There is no direct edge 1-4. Path 1->2->4 would step on 2 (unrecorded) and record it. Path 1->2->3->4 steps on 2 and 3. So impossible. So must have direct adjacency.
Thus correct.
Now, final answer.
But wait: Could there be a scenario where a vertex is adjacent to visited set but not reachable from the current node via a path that stays entirely within visited set? Since visited set is connected, it is reachable. But we need to be careful: is visited set always connected? We argued by induction: Start with {1} connected. Suppose S is connected, and we add v via edge (u,v) where u∈S. Then S∪{v} is connected because v is connected to u. However, we must ensure that we actually add v via an edge that exists from some u∈S. In our construction of the sequence, we only know that each a_i has an edge to some earlier vertex. That earlier vertex is in S_{i-1}. So indeed, when we add a_i, it is adjacent to S_{i-1}. So by induction, S_i is connected. So the visited set is always connected. So movement within visited set is always possible.
Thus all good.
Now, could the greedy algorithm be implemented with a set instead of heap? Possibly, but heap is fine.
One might ask: Is there any need to consider the case where multiple vertices have the same smallest label? No issue.
Thus solution.
Now I'll write final answer with explanation.
But wait: Let's test with a more complex graph that might cause tie-breaking issues. Suppose we have graph: 1 connected to 2 and 3; 2 connected to 4; 3 connected to 4. Greedy gives 1,2,3,4. Could there be sequence 1,2,4,3? Check: For 4 to be third, we need after {1,2}, 4 is adjacent (yes via 2). So 1,2,4 is possible? But after recording 4, visited set = {1,2,4}. Is 3 adjacent? 3 is adjacent to 1 and 4? Actually 3 adjacent to 1 and 4 (since 3-4 edge). So 3 is adjacent, so sequence 1,2,4,3 is valid. Compare with greedy 1,2,3,4. At position 3: 4 vs 3; 3 is smaller, so greedy is smaller. So good.
Now what if we have 1 connected to 2 and 4; 2 connected to 3; 4 connected to 3; and also 2 connected to 5; 4 connected to 5. Greedy: after 1, neighbors {2,4} -> pick 2. Then S={1,2}, eligible: neighbors of 1:4, neighbors of 2:3,5 -> smallest is 3? Actually 3<4 and 3<5, so pick 3. Then S={1,2,3}, eligible: neighbors of 3:2,4; so 4 and 5 (from 2) -> 4,5. Smallest 4. Then S={1,2,3,4}, eligible: 5 from 2 or 4 -> pick 5. Sequence:1,2,3,4,5. Alternative: 1,2,4,3,5. Compare at third: 3 vs 4 -> greedy smaller. Alternative: 1,4,2,3,5: at second: 4>2, so greedy smaller. So fine.
Thus all good.
Now, we must produce answer.
But hold on: There's a known Codeforces problem "Boboniu and Bit Operations" etc. Actually I recall a problem named "Bob and Wander" or something? Possibly this is from Codeforces Round #... Actually I think I've seen a problem: "Lunar New Year and a Wander" maybe? Searching memory: There's Codeforces problem 1106D? Wait, I'm not sure. But there is a problem called "Lunar New Year and a Wander" from Codeforces Round #... Actually I recall problem: "1106 D? No." Let me think: There's Codeforces Round 1106 (Div. 2) has problem "Lunar New Year and a Wander"? I'm not sure. Actually I recall a problem "D. Lunar New Year and a Wander" from Codeforces 1106? Let's check: I think it's Codeforces Round #1106 (Div. 2) had problem "C. Lunar New Year and Number Division", "D. Lunar New Year and a Wander"? Not sure. But I've definitely seen this problem before. The solution is exactly to use a priority queue to always go to the smallest unvisited neighbor. So I'm confident.
Now, final answer.
Potential pitfalls: Input size large, use fast I/O. Use vector for adjacency. Use priority_queue with greater for min-heap. Keep visited boolean.
Edge Cases: Graph with n=1, m=0. Works.
Now, I'll produce final answer in the required format.
But wait: The output examples have a trailing space after the last number? The problem statement shows a space after last number. Usually it's okay to output numbers separated by spaces, maybe with a trailing space. But to be safe, we can output without trailing space. However, the examples show a space after last number. I'll output without trailing space or with space? Usually judges accept both. I'll output with spaces between numbers and no trailing newline after last number? I'll output each number separated by space and then newline at end. That is typical.
Thus final.
Now, I'm going to write final solution with comments explaining reasoning.
But the user asked: "Lunar New Year is approaching... Bob wants to know the lexicographically smallest sequence...". So they want solution.
Thus answer: Provide code and explanation.
But as ChatGPT, I need to output final answer as code? The instruction: "Output a line containing the lexicographically smallest sequence". So the answer is the sequence. But they also expect a solution? The conversation is typical of a coding problem; the user expects me to provide solution code. In this environment, I usually respond with an explanation and then code. However, the final answer should be the output? Actually this is a problem solving scenario: The user says "Bob thinks this problem is trivial, and he wants you to solve it." So they want me to output the sequence. But the input is not given; they gave sample inputs. So they want a program? Actually the typical style: The user gives a problem statement and asks to solve it, expecting a program that reads input and prints output. In the ChatGPT context, they often want the solution code. So I will provide code.
But also, they might want explanation? Possibly. I'll provide both.
Given the instructions, I think the final answer should include the code in the appropriate language (C++). I'll provide it.
Thus final message: Explanation + C++ implementation.
Let's craft final. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n + 1);
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
if (u == v) continue; // self‑loops are irrelevant
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<bool> visited(n + 1, false);
visited[1] = true;
priority_queue<int, vector<int>, greater<int>> pq; // min‑heap of eligible vertices
for (int v : adj[1]) {
if (!visited[v]) {
pq.push(v);
}
}
vector<int> order = {1};
while ((int)order.size() < n) {
int u = pq.top();
pq.pop();
if (visited[u]) continue; // skip duplicates
visited[u] = true;
order.push_back(u);
for (int v : adj[u]) {
if (!visited[v]) {
pq.push(v);
}
}
}
for (int i = 0; i < n; ++i) {
cout << order[i] << " \n"[i == n - 1];
}
return 0;