PAT甲级真题1122 哈密顿回路(详解)

题目

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 V​1 V​2 V​n​​
1
where n is the number of vertices in the list, and V​i​​ '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

题意

给出一个无向图的顶点,边信息。然后输入一串查询数字,问,输入的这些查询数字是否能够组成一个simple cycle。

这里simple的定义指的是:不含冗余顶点
cycle的定义就是:给出的顶点集形成了一个环
如果是simple cycle,则输出YES;如果不是simple cycle,则输出NO;

#include<iostream>
#include<set>
using namespace std;

int connected[201][201];//查询两个点是否连通用邻接矩阵更好
int N,M,K;

int main(){
    cin>>N>>M;
    int i,j;//下次记得定义i,j提前定义,防止产生错误
    while(M--){
        cin>>i>>j;
        connected[i][j]=connected[j][i]=1;
    }
    cin>>K;
    
    while(K--){
        int n;
        cin>>n;
        int a[n];//路径
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        if(a[0]==a[n-1]){//是环
            if(n==N+1)//边数等于点数+1,连通
            {
                int visited[300]={0};
            for(i=1;i<n;i++){//都经过
                if(visited[a[i]])break;
                visited[a[i]]=1;
            }
             if(i==n){//正好都经过
                 for(i=1;i<n;i++){//通不通?
                     if(!connected[a[i]][a[i-1]]){//看看他跟他前面的
                         break;//不通
                     } 
                 }
                 if(i==n){
                     cout<<"YES"<<endl;
                     continue;
                 }
             }
           }
        }
        cout<<"NO"<<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值