✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1122 Hamiltonian Cycle (pintia.cn)
🔑中文翻译:哈密顿回路
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1122 Hamiltonian Cycle
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<N≤200), 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, orNO
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
题意
哈密顿回路问题是找到一个包含图中每个顶点的简单回路。
这样的回路称为“哈密顿回路”。
在本题中,你需要做的是判断给定路径是否为哈密顿回路。
思路
- 用邻接矩阵来存储每个结点之间是否存在一条边,如果存在则置为
true
。 - 判断给定的路径是否为哈密顿回路。
- 先判断首尾结点是否相同,并且给定路径结点数是否为
n+1
个点,因为首尾结点相同,所以会多出一个点。 - 然后判断该路径中每条边是否存在,并用
st
来存储出现过的结点。 - 最后再判断所有结点是否都出现过。
- 先判断首尾结点是否相同,并且给定路径结点数是否为
- 根据判断的结果输出最终答案。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 210;
int n, m;
bool g[N][N], st[N];
int nodes[N * 2];
bool check(int cnt)
{
//首尾结点必须相同,并且一共要有n个结点
if (nodes[0] != nodes[cnt - 1] || cnt != n + 1) return false;
//先判断每条边是否存在
memset(st, false, sizeof st);
for (int i = 0; i < cnt - 1; 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;
//输入边的信息
for (int i = 0; i < m; i++)
{
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)) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}