【PAT甲级】1122 Hamiltonian Cycle

✍个人博客: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, 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
题意

哈密顿回路问题是找到一个包含图中每个顶点的简单回路。

这样的回路称为“哈密顿回路”。

在本题中,你需要做的是判断给定路径是否为哈密顿回路。

思路
  1. 用邻接矩阵来存储每个结点之间是否存在一条边,如果存在则置为 true
  2. 判断给定的路径是否为哈密顿回路。
    1. 先判断首尾结点是否相同,并且给定路径结点数是否为 n+1 个点,因为首尾结点相同,所以会多出一个点。
    2. 然后判断该路径中每条边是否存在,并用 st 来存储出现过的结点。
    3. 最后再判断所有结点是否都出现过。
  3. 根据判断的结果输出最终答案。
代码
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值