基础实验6-2.2 汉密尔顿回路 (25 分)

著名的“汉密尔顿(Hamilton)回路问题”是要找一个能遍历图中所有顶点的简单回路(即每个顶点只访问 1 次)。本题就要求你判断任一给定的回路是否汉密尔顿回路。

输入格式:

在这里插入图片描述

输出格式:

对每条待检回路,如果是汉密尔顿回路,就在一行中输出"YES",否则输出"NO"。

输入样例:

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

输出样例:

YES
NO
NO
NO
YES
NO

代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int n , m;
int e[205][205] , book[205] , que[205];
int main()
{
    int x , y;
    cin>>n>>m;
    for(int i = 1 ; i <= m ; i++)
    {
        cin>>x>>y;
        e[x][y] = 1 ; e[y][x] = 1;
    }
    int k;
    cin>>k;
    while(k--)
    {
        memset(book , 0 , sizeof(book));
        int flag = 1 , tip = 0;
        int t , head , tail ,kk;
        cin>>t;
        cin>>head;
        book[head] = 1;
        kk = head;
        if(t != n+1)
            flag = 0;
        for(int i = 2 ; i < t ; i++)
        {
            cin>>tail;
            if(e[kk][tail] != 1)
                flag = 0;
            book[tail] = 1;
            kk = tail;
        }
        cin>>tail;
        if(e[kk][tail] != 1)
            flag = 0;
        for(int i = 1 ; i <= n ; i++)
            if(book[i] != 1)
               flag = 0;
            else
                tip++;
        if(flag && tip == n && tail == head)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值