Problem Description:
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 N N ( 2 < N ≤ 200 2<N\leq 200 2<N≤200), the number of vertices, and M M M, the number of edges in an undirected graph. Then M M M lines follow, each describes an edge in the format Vertex1 Vertex2
, where the vertices are numbered from 1 to N N N. The next line gives a positive integer K K K which is the number of queries, followed by K K K lines of queries, each in the format:
n V 1 V 2 … V n n\ V_1\ V_2\ \ldots\ V_n n V1 V2 … Vn
where n n n is the number of vertices in the list, and V i V_i 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 10
6 2
3 4
1 5
2 5
3 1
4 1
1 6
6 3
1 2
4 5
6
7 5 1 4 3 6 2 5
6 5 1 4 3 6 2
9 6 2 1 6 3 4 5 2 6
4 1 2 5 1
7 6 1 3 4 5 2 6
7 6 1 2 5 4 3 1
Sample Output:
YES
NO
NO
NO
YES
NO
Problem Analysis:
前置知识:
-
哈密顿路径:由指定的起点前往指定的终点,途中经过所有其他节点且只经过一次的路径
-
哈密顿回路:闭合的哈密顿路径称作哈密顿回路(Hamiltonian cycle)
-
哈密顿图:包含哈密顿回路的图
本题只需要从定义出发判断给定的序列是否是哈密顿回路,即只需满足以下四个条件,即使哈密顿回路的路径序列:
- 序列总点数必须等于 n + 1 n + 1 n+1
- 首尾必须是同一个点
- 每个点能且只能出现一次,起始点除外,可以出现两次
- 每个点的前驱必须是合法的,即不能出现不存在的边
Code
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 210;
int n, m;
bool g[N][N], st[N];
int nodes[N * 2];
bool check(int cnt)
{
if (nodes[0] != nodes[cnt - 1] || cnt != n + 1) return false;
memset(st, 0, sizeof st);
for (int i = 0; i < cnt; i ++ )
{
st[nodes[i]] = true;
if (!g[nodes[i]][nodes[i + 1]])
return false;
}
for (int i = 1; i <= n; i ++ )
if (!st[i])
return false;
return true;
}
int main()
{
cin >> n >> m;
while (m -- )
{
int a, b;
cin >> a >> b;
g[a][b] = g[b][a] = true;
}
int k;
cin >> k;
while (k -- )
{
int cnt;
cin >> cnt;
for (int i = 0; i < cnt; i ++ ) cin >> nodes[i];
if (check(cnt)) puts("YES");
else puts("NO");
}
return 0;
}