AtCoder:Hamiltonish Path(思维 & dfs)

B - Hamiltonish Path


Time limit : 2sec / Memory limit : 256MB

Score : 500 points

Problem Statement

You are given a connected undirected simple graph, which has N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1through M. Edge i connects vertices Ai and Bi. Your task is to find a path that satisfies the following conditions:

  • The path traverses two or more vertices.
  • The path does not traverse the same vertex more than once.
  • A vertex directly connected to at least one of the endpoints of the path, is always contained in the path.

It can be proved that such a path always exists. Also, if there are more than one solution, any of them will be accepted.

Constraints

  • 2N105
  • 1M105
  • 1Ai<BiN
  • The given graph is connected and simple (that is, for every pair of vertices, there is at most one edge that directly connects them).

Input

Input is given from Standard Input in the following format:

N M
A1 B1
A2 B2
:
AM BM

Output

Find one path that satisfies the conditions, and print it in the following format. In the first line, print the count of the vertices contained in the path. In the second line, print a space-separated list of the indices of the vertices, in order of appearance in the path.


Sample Input 1

Copy
5 6
1 3
1 4
2 3
1 5
3 5
2 4

Sample Output 1

Copy
4
2 3 1 4

There are two vertices directly connected to vertex 2: vertices 3 and 4. There are also two vertices directly connected to vertex 4: vertices 1 and 2. Hence, the path 2 → 3 → 1 → 4 satisfies the conditions.


Sample Input 2

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

Sample Output 2

Copy
7
1 2 3 4 5 6 7
题意:给一个无向图,要求找出一条路符合以下要求:起始点的相邻点都要包含在路径中,同一个点只能经过一次。

思路:直接看作者题解吧:

First, consider an arbitrary path. Check if this path satisfies the conditions. If yes, we are done.Otherwise, we can find a vertex that is adjacent to one of the endpoints of the path. We can extend the path using this vertex and we get a longer path. We repeat this process, and this process finishes after at most N − 1 steps since the length of any path is at most N − 1.For example, we can implement this idea as follows:1. Create a deque with single vertex: {1}.

2. Let x be the first element of the deque, and y be the last element of the deque. Repeat the following:(a)For each vertex z that is adjacent to x, check if z is contained in the path. If not, append it to the beginning of the deque and go to step 2.(b)For each vertex z that is adjacent to y, check if z is contained in the path. If not, append it to the end of the deque and go to step 2.

3. End the process. We found a solution.

In step 2(a) and step 2(b), each vertex is processed at most once. Therefore, this solution works in O(M).

# include 
using namespace std;

const int N = 1e5+3;
vectorv[N];
bool vis[N];
listL;

void dfs(int u, bool des)
{
    for(int i=0; i


你可能感兴趣的:(DFS)