The "Hamilton cycle problem" is to find a simple cycle that contains every vertex in a graph. Such a cycle is called a "Hamiltonian cycle".
In this problem, you are supposed to tell if a given cycle is a Hamiltonian cycle.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive integers N (2), the number of vertices, and M, the number of edges in an undirected graph. Then M lines follow, each describes an edge in the format Vertex1 Vertex2
, where the vertices are numbered from 1 to N. The next line gives a positive integer K which is the number of queries, followed by K lines of queries, each in the format:
n V1 V2 ... Vn
where n is the number of vertices in the list, and Vi's are the vertices on a path.
Output Specification:
For each query, print in a line YES
if the path does form a Hamiltonian cycle, or NO
if not.
Sample Input:
6 106 23 41 52 53 14 11 66 31 24 567 5 1 4 3 6 2 56 5 1 4 3 6 29 6 2 1 6 3 4 5 2 64 1 2 5 17 6 1 3 4 5 2 67 6 1 2 5 4 3 1
Sample Output:
YESNONONOYESNO 第一,遍历点K一定等于N+1,因为既要遍历且一次所有顶点,而且回到起点 第二,遍历的最后一个点一定是起点 使用visit记录顶点是否遍历过了,graph记录路径是否能行
1 #include2 #include 3 using namespace std; 4 int main() 5 { 6 int n, m, k, a, b, start, graph[205][205]; 7 bool visit[205];//记录每个顶点遍历一次 8 fill(graph[0], graph[0] + 25 * 205, -1); 9 cin >> n >> m;10 while (m--)11 {12 cin >> a >> b;13 graph[a][b] = graph[b][a] = 1;14 }15 cin >> m;16 while (m--)17 {18 cin >> k;19 bool flag = true;20 fill(visit, visit + 205, false);21 for (int i = 0; i < k; ++i)22 {23 cin >> b;24 if (flag == false || k != n + 1)//遍历所有的顶点并回到起点,则一定走过n+1个点25 {26 flag = false;27 continue;28 }29 if (i == 0)30 start = b;//记录起点31 else if (graph[a][b] != 1)//此路不通32 flag = false;33 else if (i == k - 1 && b != start)//最后一个点不是起点34 flag = false;35 else if (i != k - 1 && visit[b] != false)//除了最后一次重复遍历起点,出现了其他点重复遍历,36 flag = false;37 else38 visit[b] = true;//遍历过39 a = b;//记录前一个点40 }41 if (flag)42 {43 for (int i = 1; i <= n && flag == true; ++i)44 if (visit[i] == false)//存在没有遍历的顶点45 flag = false;46 if (flag)47 cout << "YES" << endl;48 }49 if (flag == false)50 cout << "NO" << endl;51 }52 return 0; 53 }